package com.xbongbong.paas.print.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasAppEntity;
import com.xbongbong.paas.domain.entity.PaasFormEntity;
import com.xbongbong.paas.domain.entity.PaasFormExplainEntity;
import com.xbongbong.paas.domain.entity.PaasKitPrintTemplateEntity;
import com.xbongbong.paas.domain.entity.PaasMenuEntity;
import com.xbongbong.paas.domain.entity.PaasPrintTemplateEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormEntityExt;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.MenuTypeEnum;
import com.xbongbong.paas.enums.ProcessSaasFormEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.field.ItemPoJo;
import com.xbongbong.paas.field.LinkInfoPojo;
import com.xbongbong.paas.field.LinkedAttrPoJo;
import com.xbongbong.paas.field.SubFormPoJo;
import com.xbongbong.sys.help.PackageHelp;
import com.xbongbong.paas.log.MongoLogHelp;
import com.xbongbong.paas.log.constant.LogMemoConstant;
import com.xbongbong.paas.model.PaasAppModel;
import com.xbongbong.paas.model.PaasFormModel;
import com.xbongbong.paas.model.PaasMenuModel;
import com.xbongbong.paas.pojo.dto.FormGetDTO;
import com.xbongbong.paas.pojo.vo.FormEntityGetVO;
import com.xbongbong.paas.pojo.vo.FormGetVO;
import com.xbongbong.paas.print.enums.AdditionalPrintAttrEnum;
import com.xbongbong.paas.print.helper.PrintHelper;
import com.xbongbong.paas.print.manager.feign.FormFeignClient;
import com.xbongbong.paas.print.manager.feign.WorkOrderPrintClient;
import com.xbongbong.paas.print.model.PaasKitPrintTemplateModel;
import com.xbongbong.paas.print.model.PaasPrintTemplateModel;
import com.xbongbong.paas.print.pojo.FieldAttrPojo;
import com.xbongbong.paas.print.pojo.dto.PaasPrintAddDTO;
import com.xbongbong.paas.print.pojo.dto.PaasPrintEditDTO;
import com.xbongbong.paas.print.pojo.dto.PaasPrintGetDataByProcessDTO;
import com.xbongbong.paas.print.pojo.dto.PaasPrintGetDataDTO;
import com.xbongbong.paas.print.pojo.dto.PaasPrintGetDatasByProcessDTO;
import com.xbongbong.paas.print.pojo.dto.PaasPrintGetDatasDTO;
import com.xbongbong.paas.print.pojo.dto.PaasPrintGetDefaultDTO;
import com.xbongbong.paas.print.pojo.dto.PaasPrintListDTO;
import com.xbongbong.paas.print.pojo.dto.PaasPrintManageListDTO;
import com.xbongbong.paas.print.pojo.dto.PaasPrintNameEditDTO;
import com.xbongbong.paas.print.pojo.dto.PaasPrintTemplateSortDTO;
import com.xbongbong.paas.print.pojo.dto.PaasPrintUpdateDTO;
import com.xbongbong.paas.print.pojo.dto.SubFormAttrDataDTO;
import com.xbongbong.paas.print.pojo.vo.PaasPrintEditVO;
import com.xbongbong.paas.print.pojo.vo.PaasPrintFormListVO;
import com.xbongbong.paas.print.pojo.vo.PaasPrintItemVO;
import com.xbongbong.paas.print.pojo.vo.PaasPrintListVO;
import com.xbongbong.paas.print.pojo.vo.PaasPrintManageItemVO;
import com.xbongbong.paas.print.pojo.vo.PaasPrintManageListVO;
import com.xbongbong.paas.print.pojo.vo.PaasPrintNameEditVO;
import com.xbongbong.paas.print.pojo.vo.PaasPrintSaveVO;
import com.xbongbong.paas.print.pojo.vo.PrintDisplayAttrVO;
import com.xbongbong.paas.print.pojo.vo.SubFormAttrDataVO;
import com.xbongbong.paas.print.service.PaasPrintService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.pojo.AppPermissionPojo;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.paas.toolbox.util.JsonHelperUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.wrap.BaseDTO;
import com.xbongbong.paas.toolbox.wrap.BaseVO;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.pro.constant.BusinessConstant;
import com.xbongbong.pro.constant.I18nStringConstant;
import com.xbongbong.pro.constant.PrintConstant;
import com.xbongbong.pro.enums.ErrorCodeEnum;
import com.xbongbong.pro.enums.PrintCustomerStatementDetailEnum;
import com.xbongbong.pro.enums.PrintInvoicePurchaseTotalMoneyEnum;
import com.xbongbong.pro.enums.PrintInvoiceTotalMoneyEnum;
import com.xbongbong.pro.enums.PrintPaySheetAmountEnum;
import com.xbongbong.pro.enums.PrintPaymentSheetAmountEnum;
import com.xbongbong.pro.enums.PrintSceneTypeEnum;
import com.xbongbong.pro.enums.PrintSpecialAttrEnum;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.StatisticOptionEnum;
import com.xbongbong.pro.enums.errorcodes.PrintErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.formexplain.pojo.dto.ExplainMapLinkDataDTO;
import com.xbongbong.pro.formexplain.pojo.dto.ProductExplainDTO;
import com.xbongbong.pro.formexplain.pojo.vo.ExplainMapLinkDataVO;
import com.xbongbong.pro.process.pojo.ProcessFormFilterPojo;
import com.xbongbong.pro.process.pojo.dto.ProcessFormFilterDTO;
import com.xbongbong.pro.process.pojo.vo.ProcessFormFilterVO;
import com.xbongbong.pro.template.pojo.dto.TemplateDTO;
import com.xbongbong.pro.template.pojo.dto.TemplateSortDTO;
import com.xbongbong.pro.template.pojo.vo.EnableVO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.MultiUnitConstant;
import com.xbongbong.saas.constant.ProductConstant;
import com.xbongbong.saas.constant.StockConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.WorkOrderExplainEntity;
import com.xbongbong.saas.domain.entity.WorkOrderFormEntity;
import com.xbongbong.saas.domain.entity.WorkOrderTemplateCategoryEntity;
import com.xbongbong.saas.domain.entity.WorkOrderTemplateEntity;
import com.xbongbong.saas.domain.entity.WorkReportSetEntity;
import com.xbongbong.saas.domain.entity.ext.WorkOrderFormEntityExt;
import com.xbongbong.saas.domain.entity.ext.WorkOrderTemplateEntityExt;
import com.xbongbong.saas.enums.CompanyConfigEnum;
import com.xbongbong.saas.enums.CustomerStatementEnum;
import com.xbongbong.saas.enums.CustomerStatementProductEnum;
import com.xbongbong.saas.enums.OperateModuleTypeEnum;
import com.xbongbong.saas.enums.OperateTypeEnum;
import com.xbongbong.saas.enums.OutstockSaleRelativeConstantEnum;
import com.xbongbong.saas.enums.PrintMenuEnum;
import com.xbongbong.saas.enums.ProductPrintHelpEnum;
import com.xbongbong.saas.enums.SelectProductEnum;
import com.xbongbong.saas.enums.ShowTypeEnum;
import com.xbongbong.saas.enums.UpdateDataTypeEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.PurchaseEnum;
import com.xbongbong.saas.enums.business.ReceiptOrderEnum;
import com.xbongbong.saas.enums.business.WorkReportDailyEnum;
import com.xbongbong.saas.enums.business.WorkReportPlanEnum;
import com.xbongbong.saas.enums.business.WorkReportTypeEnum;
import com.xbongbong.saas.model.WorkOrderFormModel;
import com.xbongbong.saas.model.WorkOrderTemplateCategoryModel;
import com.xbongbong.saas.model.WorkOrderTemplateModel;
import com.xbongbong.saas.model.WorkReportSetModel;
import com.xbongbong.sys.domain.entity.CompanyConfigEntity;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.model.CompanyConfigModel;
import com.xbongbong.sys.model.UserModel;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 * 创建时间： 2018/9/11 10:51
 * 修改时间： 2018/9/11 10:51 梁鲁江
 *
 * @author 梁鲁江
 */
@Service("paasPrintService")
public class PaasPrintServiceImpl implements PaasPrintService {
    private static final Logger LOG = LoggerFactory.getLogger(PaasPrintServiceImpl.class);
    @Resource
    private PaasPrintTemplateModel paasPrintTemplateModel;
    @Resource
    private FormFeignClient formFeignClient;
    @Resource
    private MongoLogHelp mongoLogHelp;
    @Resource
    private UserModel userModel;
    @Resource
    private PaasMenuModel paasMenuModel;
    @Resource
    private PaasAppModel paasAppModel;
    @Resource
    private PaasFormModel paasFormModel;
    @Resource
    private PrintHelper printHelper;
    @Resource
    private CompanyConfigModel companyConfigModel;
    @Resource
    private WorkReportSetModel workReportSetModel;
    @Resource
    private WorkOrderFormModel workOrderFormModel;
    @Resource
    private WorkOrderTemplateModel workOrderTemplateModel;
    @Resource
    private WorkOrderTemplateCategoryModel workOrderTemplateCategoryModel;
    @Resource
    private PaasKitPrintTemplateModel paasKitPrintTemplateModel;
    @Resource
    private PackageHelp packageHelp;
    @Resource
    private WorkOrderPrintClient workOrderPrintClient;

    @Override
    public PaasPrintEditVO getDefaultPrintTemplate(PaasPrintGetDefaultDTO paasPrintGetDefaultDTO) throws XbbException {
        String userId = paasPrintGetDefaultDTO.getUserId();
        String corpid = paasPrintGetDefaultDTO.getCorpid();
        UserEntity logUser = userModel.getByKey(userId, corpid);
        if (logUser == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100004.getCode(), MessageConstant.USER_NOT_EXIST);
        }
        PaasPrintEditVO paasPrintEditVO = new PaasPrintEditVO();
        PaasPrintTemplateEntity entity;
        // 应用场景
        Integer sceneType = paasPrintGetDefaultDTO.getSceneType();
        if (Objects.isNull(sceneType)) {
            sceneType = PrintSceneTypeEnum.DEFAULT.getCode();
        }
        // 套打模板
        if (!Objects.equals(PrintSceneTypeEnum.DEFAULT.getCode(), sceneType)) {
            getKitPrintTemplate(corpid, paasPrintGetDefaultDTO.getKitPrintTemplateId(), paasPrintEditVO.getBusinessType(), paasPrintEditVO);
            return paasPrintEditVO;
        }
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("corpid", "0");
        param.put("businessType", paasPrintGetDefaultDTO.getBusinessType());
        param.put("del", 0);
        param.put("distributorMark", paasPrintGetDefaultDTO.getDistributorMark());
        List<PaasPrintTemplateEntity> list = paasPrintTemplateModel.list(param);
        if (list.size() <= 0) {
            return paasPrintEditVO;
        }
        entity = list.get(0);
        BeanUtil.copyProperties(entity, paasPrintEditVO);
        paasPrintEditVO.setHtml(JsonHelperUtil.parseArray(entity.getHtml()));
        // paasPrintEditVO.setConfigInfo(JsonHelperUtil.parseObject(entity.getConfigInfo()));
        paasPrintEditVO.setBusinessType(paasPrintGetDefaultDTO.getBusinessType());
        JSONObject parse = (JSONObject) JSONObject.parse(entity.getConfigInfo());
        dealDefaultPrint(parse);
        paasPrintEditVO.setConfigInfo(parse);
        return paasPrintEditVO;
    }

    /**
     * 处理默认页眉页脚页码字段
     *
     * @param parse
     * @return
     */
    private void dealDefaultPrint(JSONObject parse) {
        if (Objects.isNull(parse.get("header"))) {
            JSONObject header = new JSONObject();
            header.put("textContent", "");
            header.put("enable", 0);
            header.put("footName", "Alias");
            header.put("fontSize", 12);
            header.put("space", 3);
            header.put("showLine", 0);
            parse.put("header", header);
        }
        if (Objects.isNull(parse.get("footer"))) {
            JSONObject footer = new JSONObject();
            footer.put("textContent", "");
            footer.put("enable", 0);
            footer.put("footName", "Alias");
            footer.put("fontSize", 12);
            footer.put("space", 3);
            footer.put("showLine", 0);
            parse.put("footer", footer);
        }
        if (Objects.isNull(parse.get("page"))) {
            JSONObject page = new JSONObject();
            page.put("enable", 0);
            page.put("location", 1);
            page.put("alignment", 1);
            page.put("pageHeight", 0);
            parse.put("page", page);
        }
        if (Objects.isNull(parse.get("size"))) {
            parse.put("size", "A4-vertical");
        }
        if (Objects.isNull(parse.get("padding"))) {
            JSONObject padding = new JSONObject();
            padding.put("top", 20);
            padding.put("left", 20);
            padding.put("right", 20);
            padding.put("bottom", 20);
            parse.put("padding", padding);
        }
    }

    @Override
    public PaasPrintSaveVO addPaasPrintTemplate(PaasPrintAddDTO paasPrintAddDTO) throws XbbException {
        //登录用户
        String userId = paasPrintAddDTO.getUserId();
        String corpid = paasPrintAddDTO.getCorpid();
        UserEntity logUser = userModel.getByKey(userId, corpid);
        if (logUser == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100004.getCode(), MessageConstant.USER_NOT_EXIST);
        }
        Long formId = paasPrintAddDTO.getFormId();
        PaasFormEntity paasFormEntity = new PaasFormEntity();
        if (Objects.equals(paasPrintAddDTO.getBusinessType(), XbbRefTypeEnum.WORK_ORDER.getCode())) {
            WorkOrderFormEntityExt byKey = workOrderFormModel.getByKey(formId, paasPrintAddDTO.getCorpid());
            BeanUtil.copyProperties(byKey, paasFormEntity);
        } else {
            paasFormEntity = paasFormModel.getByKey(formId, corpid);
        }
        if (paasFormEntity == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100018.getCode(), I18nStringConstant.FORM_NOT_EXIST);
        }
        int limitValue = PrintConstant.LIMIT_SIZE;
        CompanyConfigEntity companyConfig = companyConfigModel.getConfigEntity(corpid, CompanyConfigEnum.PRINT_LIMT_NUM.getAlias());
        if (companyConfig != null && !StringUtil.isEmpty(companyConfig.getConfigValue())) {
            limitValue = StringUtil.toInt(companyConfig.getConfigValue(), limitValue);
        }
        // 场景类型
        Integer sceneType = paasPrintAddDTO.getSceneType();
        PrintSceneTypeEnum printSceneTypeEnum = PrintSceneTypeEnum.getByCode(sceneType);
        if (Objects.isNull(printSceneTypeEnum)) {
            sceneType = null;
        }

        Map<String, Object> printParam = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        printParam.put("corpid", corpid);
        printParam.put("del", 0);
        printParam.put("appId", paasFormEntity.getAppId());
        printParam.put("menuId", paasFormEntity.getMenuId());
        printParam.put("formId", paasPrintAddDTO.getFormId());
        Integer count = paasPrintTemplateModel.getEntitysCount(printParam);
        if (count != null && count >= limitValue) {
            throw new XbbException(PrintErrorCodeEnum.API_ERROR_2320012.getCode(), PrintErrorCodeEnum.API_ERROR_2320012.getMsg() + limitValue);
        }
        //实体
        PaasPrintTemplateEntity entity = new PaasPrintTemplateEntity();
        BeanUtil.copyProperties(paasPrintAddDTO, entity);
        entity.setCreatorId(paasPrintAddDTO.getUserId());
        entity.setAppId(paasFormEntity.getAppId());
        entity.setMenuId(paasFormEntity.getMenuId());
        entity.setDistributorMark(paasFormEntity.getDistributorMark());
        if (Objects.nonNull(sceneType)) {
            entity.setSceneType(sceneType);
        }

        PaasPrintSaveVO paasPrintSaveVO = new PaasPrintSaveVO();
        try {
            paasPrintTemplateModel.save(entity);
            paasPrintSaveVO.setId(entity.getId());
        } catch (Exception e) {
            LOG.error("打印模板数据库保存出错", e);
            throw new XbbException(PrintErrorCodeEnum.API_ERROR_232002);
        }

        // 记录日志
        String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_ADD_PRINT_TEMPLATE), logUser.getName(), entity.getName());
        try {
            mongoLogHelp.buildLog(corpid, logUser.getUserId(), logUser.getName(), OperateModuleTypeEnum.PAAS_PRINT, OperateTypeEnum.NEW, entity.getId().toString(), entity.getName(), memo, paasPrintAddDTO.getHttpHeader());
        } catch (Exception e) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, I18nStringConstant.LOGGING_FAILED);
        }

        return paasPrintSaveVO;
    }

    @Override
    public PaasPrintSaveVO updatePaasPrintTemplate(PaasPrintUpdateDTO paasPrintUpdateDTO) throws XbbException {
        String corpid = paasPrintUpdateDTO.getCorpid();
        String userId = paasPrintUpdateDTO.getUserId();
        //登录用户
        UserEntity logUser = userModel.getByKey(userId, corpid);
        if (logUser == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001.getCode(), MessageConstant.USER_NOT_EXIST);
        }
        Long id = paasPrintUpdateDTO.getId();
        PaasPrintTemplateEntity entity = paasPrintTemplateModel.getByKey(id, corpid);
        if (entity == null) {
            throw new XbbException(PrintErrorCodeEnum.API_ERROR_2320011, PrintErrorCodeEnum.API_ERROR_2320011.getMsg());
        }
        BeanUtil.copyProperties(paasPrintUpdateDTO, entity, true);
        PaasPrintSaveVO paasPrintSaveVO = new PaasPrintSaveVO();
        try {
            paasPrintTemplateModel.update(entity);
        } catch (Exception e) {
            LOG.error("打印模板数据库更新出错", e);
            throw new XbbException(PrintErrorCodeEnum.API_ERROR_232003, PrintErrorCodeEnum.API_ERROR_232003.getMsg());
        }

        // 记录日志
        Integer del = entity.getDel();
        String logMemoUpdateTemplate = I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_UPDATE_TEMPLATE);
        OperateTypeEnum operateTypeEnum = OperateTypeEnum.EDIT;
        if (del != null && del == 1) {
            logMemoUpdateTemplate = I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_DELETE_TEMPLATE);
            operateTypeEnum = OperateTypeEnum.DELETE;
        }
        String memo = String.format(logMemoUpdateTemplate, logUser.getName(), entity.getName());
        mongoLogHelp.buildLog(corpid, logUser.getUserId(), logUser.getName(), OperateModuleTypeEnum.PAAS_PRINT, operateTypeEnum, entity.getId().toString(), entity.getName(), memo, paasPrintUpdateDTO.getHttpHeader());

        paasPrintSaveVO.setId(id);
        return paasPrintSaveVO;
    }

    @Override
    public PaasPrintEditVO editPaasPrintTemplate(PaasPrintEditDTO paasPrintEditDTO) throws XbbException {
        Long id = paasPrintEditDTO.getId();
        PaasPrintEditVO paasPrintEditVO = new PaasPrintEditVO();
        PaasPrintTemplateEntity entity = paasPrintTemplateModel.getByKey(id, paasPrintEditDTO.getCorpid());
        if (entity == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, I18nStringConstant.TEMPLATE_NOT_EXIST);
        }
        // PaasFormEntityExt paasFormEntityExt = paasFormModel.getByKey(entity.getFormId(),paasPrintEditDTO.getCorpid());
        // if (paasFormEntityExt == null) {
        //     throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, I18nStringConstant.FORM_NOT_EXIST);
        // }
        Integer sceneType = paasPrintEditDTO.getSceneType();
        if (Objects.isNull(sceneType)) {
            sceneType = PrintSceneTypeEnum.DEFAULT.getCode();
        }
        BeanUtil.copyProperties(entity, paasPrintEditVO);
        JSONArray html = setHtml4Product(entity.getHtml());
        paasPrintEditVO.setHtml(html);
        JSONObject parse = JsonHelperUtil.parseObject(entity.getConfigInfo());
        if (Objects.equals(PrintSceneTypeEnum.DEFAULT.getCode(), sceneType)) {
            // 添加页眉页脚
            dealDefaultPrint(parse);
        }
        paasPrintEditVO.setConfigInfo(parse);
        paasPrintEditVO.setBusinessType(paasPrintEditDTO.getBusinessType());
        return paasPrintEditVO;
    }

    @Override
    public PaasPrintListVO list(PaasPrintListDTO paasPrintListDTO) throws XbbException {
        PaasPrintListVO paasPrintListVO = new PaasPrintListVO();
        List<PaasPrintTemplateEntity> list;
        String corpid = paasPrintListDTO.getCorpid();
        // 查询关联表单
        List<Long> formIdIn = new ArrayList<>();
        // businessType
        Integer businessType = null;
        // 表单id-名称映射
        Map<Long, String> formNameMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        HashMap<String, Object> params = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        try {
            params.put("corpid", paasPrintListDTO.getCorpid());
            params.put("appId", paasPrintListDTO.getAppId());
            params.put("menuId", paasPrintListDTO.getMenuId());
            params.put("del", DelEnum.NORMAL.getDel());
            params.put("orderByStrGroup", "form_id asc,sort asc");
            //params.put("orderByStrGroup", "formId desc");
            String alias = paasPrintListDTO.getAlias();
            if (Objects.equals(alias, XbbRefTypeEnum.WORK_ORDER.getAlias()) || Objects.equals(paasPrintListDTO.getBusinessType(), XbbRefTypeEnum.WORK_ORDER.getCode())) {
                // 根据工单模板id查询对应的工单表单id,继而查询工单默认打印模板
                WorkOrderFormEntityExt byTemplateId = null;
                if (!Objects.equals(paasPrintListDTO.getTemplateId(), 0L)) {
                    // 因为不同接口返回的值不同,所以进行特殊处理
                    if (Objects.nonNull(paasPrintListDTO.getTemplateId())) {
                        byTemplateId = workOrderFormModel.getByTemplateId(paasPrintListDTO.getTemplateId(), paasPrintListDTO.getCorpid());
                    } else {
                        byTemplateId = workOrderFormModel.getByKey(paasPrintListDTO.getFormId(), paasPrintListDTO.getCorpid());
                    }
                    businessType = XbbRefTypeEnum.WORK_ORDER.getCode();
                    formNameMap.put(byTemplateId.getId(), byTemplateId.getName());
                } else {
                    return paasPrintListVO;
                }
                params.remove("menuId");
                params.put("formId", byTemplateId.getId());
                list = paasPrintTemplateModel.list(params);
            } else if (Objects.equals(paasPrintListDTO.getBusinessType(), XbbRefTypeEnum.CUSTOMER_STATEMENT.getCode())) {
                // 获取生成对账单的formId
                PaasFormEntityExt paasFormEntityExt = paasFormModel.getByBusinessType4Distributor(XbbRefTypeEnum.CUSTOMER_STATEMENT.getCode(), corpid, paasPrintListDTO.getDistributorMark(), null);
                params.put("formId", paasFormEntityExt.getId());
                params.put("columns", "id,app_id,form_id,name,config_info,scene_type,sort");
                list = paasPrintTemplateModel.list(params);
            } else {
                params.put("formId", paasPrintListDTO.getFormId());
                params.put("columns", "id,app_id,form_id,name,config_info,scene_type,sort");
                list = paasPrintTemplateModel.list(params);
            }
        } catch (Exception e) {
            LOG.error("print数据库查询列表出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        if (list == null) {
            list = new ArrayList<>();
        }

        for (PaasPrintTemplateEntity paasPrintTemplateEntity : list) {
            Long formId = paasPrintTemplateEntity.getFormId();
            formIdIn.add(formId);
        }
        List<PaasFormEntityExt> paasFormEntityList = null;
        if (!Objects.equals(XbbRefTypeEnum.WORK_ORDER.getAlias(), paasPrintListDTO.getAlias()) && !Objects.equals(XbbRefTypeEnum.WORK_ORDER.getCode(), paasPrintListDTO.getBusinessType())) {
            params.clear();
            params.put("corpid", corpid);
            params.put("appId", paasPrintListDTO.getAppId());
            params.put("menuId", paasPrintListDTO.getMenuId());
            params.put("idIn", formIdIn);
            paasFormEntityList = paasFormModel.list(params);
            if (CollectionsUtil.isEmpty(paasFormEntityList)) {
                return paasPrintListVO;
            }
            businessType = paasFormEntityList.get(0).getBusinessType();
            paasFormEntityList.forEach((paasFormEntity) -> {
                String name = paasFormEntity.getName();
                Long id = paasFormEntity.getId();
                formNameMap.put(id, name);
            });
        }

        Map<Long, List<PaasPrintTemplateEntity>> formIdPrintTemplateListMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        for (PaasPrintTemplateEntity paasPrintTemplateEntity : list) {
            Long formId = paasPrintTemplateEntity.getFormId();
            List<PaasPrintTemplateEntity> itemList = formIdPrintTemplateListMap.get(formId);
            if (CollectionUtils.isEmpty(itemList)) {
                List<PaasPrintTemplateEntity> listPrintList = new ArrayList<>();
                listPrintList.add(paasPrintTemplateEntity);
                formIdPrintTemplateListMap.put(formId, listPrintList);
            } else {
                itemList.add(paasPrintTemplateEntity);
            }
        }
        List<PaasPrintFormListVO> listPrintList = new ArrayList<>();
        Integer finalBusinessType = businessType;
        formIdPrintTemplateListMap.forEach((key, value) -> {
            PaasPrintTemplateEntity tempItem = value.get(0);
            Long formId = tempItem.getFormId();
            String formName = formNameMap.get(formId) == null ? "" : formNameMap.get(formId);
            PaasPrintFormListVO paasPrintFormListVO =
                    new PaasPrintFormListVO(tempItem.getAppId(), tempItem.getFormId(), tempItem.getMenuId(), formName, tempItem.getBusinessType());
            List<PaasPrintItemVO> items = new ArrayList<>();
            value.forEach(temp -> {
                // 判断模板是否三联单
                JSONObject configInfo = JsonHelperUtil.parseObject(temp.getConfigInfo());
                String size = configInfo.getString("size") == null ? "" : configInfo.getString("size");
                int isDivision = size.contains("division") ? 1 : 0;
                PaasPrintItemVO paasPrintItemVO = new PaasPrintItemVO();
                paasPrintItemVO.setAppId(tempItem.getAppId());
                paasPrintItemVO.setFormId(tempItem.getFormId());
                paasPrintItemVO.setMenuId(tempItem.getMenuId());
                paasPrintItemVO.setFormName(formName);
                paasPrintItemVO.setId(temp.getId());
                paasPrintItemVO.setName(temp.getName());
                paasPrintItemVO.setIsDivision(isDivision);
                paasPrintItemVO.setSort(temp.getSort());
                paasPrintItemVO.setBusinessType(finalBusinessType);
                // 打印场景
                if (Objects.nonNull(temp.getSceneType())) {
                    paasPrintItemVO.setSceneType(temp.getSceneType());
                } else {
                    paasPrintItemVO.setSceneType(PrintSceneTypeEnum.DEFAULT.getCode());
                }
                items.add(paasPrintItemVO);
            });
            paasPrintFormListVO.setItems(items);
            listPrintList.add(paasPrintFormListVO);
        });
        paasPrintListVO.setListPrintList(listPrintList);
        return paasPrintListVO;
    }

    public PaasPrintManageListVO manageList(PaasPrintManageListDTO paasPrintManageListDTO) throws XbbException {
        PaasPrintManageListVO paasPrintManageListVO = new PaasPrintManageListVO();
        String corpid = paasPrintManageListDTO.getCorpid();
        Long appId = paasPrintManageListDTO.getAppId();
        PaasAppEntity paasAppEntity = paasAppModel.getByKey(appId, corpid);
        if (paasAppEntity == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, SystemErrorCodeEnum.API_ERROR_100028.getMsg());
        }
        String paasAppAlias = paasAppEntity.getAlias();

        //不推荐这种写法
        //Map<String, Object> params = BeanUtil.convertBean2Map(paasPrintManageListDTO);
        Map<String, Object> params = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        params.put("corpid", paasPrintManageListDTO.getCorpid());
        params.put("appId", paasPrintManageListDTO.getAppId());
        List<PaasPrintManageItemVO> list = new ArrayList<>();
        Map<Long, List<PaasPrintManageItemVO>> menuMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);

        //***********************设置查询菜单方式*************STATRT
        //0是默认不属于下面任何一个情况
        paasAppAlias = StringUtil.isEmpty(paasAppAlias) ? XbbRefTypeEnum.PAAS.getAlias() : paasAppAlias;
        XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByAlias(paasAppAlias);


        //***********************设置查询菜单方式*************END

        switch (xbbRefTypeEnum) {
            case WORK_ORDER: {
                // 获取工单分类
                // 查出对应的工单分类
                params.put("del", DelEnum.NORMAL.getDel());
                List<PaasMenuEntity> menuList = paasMenuModel.list(params);
                Long menuId = menuList.get(0).getId();
                params.remove("columns");
                List<WorkOrderTemplateCategoryEntity> workOrderTemplateCategoryEntities = workOrderTemplateCategoryModel.findEntitys(params);
                if (workOrderTemplateCategoryEntities.isEmpty()) {
                    return paasPrintManageListVO;
                }
                // 工单分类一级菜单
                List<Long> categoryIds = new ArrayList<>();
                HashMap<Long, PaasPrintManageItemVO> paasPrintHashMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                for (WorkOrderTemplateCategoryEntity workOrderTemplateCategoryEntity : workOrderTemplateCategoryEntities) {
                    PaasPrintManageItemVO paasPrintManageItemVO = new PaasPrintManageItemVO();
                    List<PaasPrintManageItemVO> subMenuList = new ArrayList<>();
                    paasPrintManageItemVO.setAlias(paasAppAlias);
                    paasPrintManageItemVO.setMenuId(menuId);
                    paasPrintManageItemVO.setName(workOrderTemplateCategoryEntity.getName());
                    paasPrintManageItemVO.setCategoryId(workOrderTemplateCategoryEntity.getId());
                    paasPrintManageItemVO.setSaasMark(SaasMarkEnum.SAAS.getCode());
                    paasPrintManageItemVO.setBusinessType(XbbRefTypeEnum.WORK_ORDER.getCode());
                    paasPrintManageItemVO.setId(workOrderTemplateCategoryEntity.getId());
                    paasPrintManageItemVO.setParentId(0L);
                    paasPrintManageItemVO.setSubMenuList(subMenuList);
                    categoryIds.add(workOrderTemplateCategoryEntity.getId());
                    paasPrintHashMap.put(workOrderTemplateCategoryEntity.getId(), paasPrintManageItemVO);
                }
                // 查对应分类的工单模板
                // 工单模板二级菜单
                params.clear();
                params.put("categoryIdIn", categoryIds);
                params.put("corpid", paasPrintManageListDTO.getCorpid());
                params.put("del", DelEnum.NORMAL.getDel());
                List<WorkOrderTemplateEntityExt> workOrderTemplateEntityExtList = workOrderTemplateModel.findEntitys(params);
                for (WorkOrderTemplateEntity workOrderTemplateEntityExt : workOrderTemplateEntityExtList) {
                    PaasPrintManageItemVO paasPrintManageItemVO = new PaasPrintManageItemVO();
                    paasPrintManageItemVO.setAlias(paasAppAlias);
                    paasPrintManageItemVO.setName(workOrderTemplateEntityExt.getName());
                    paasPrintManageItemVO.setBusinessType(XbbRefTypeEnum.WORK_ORDER.getCode());
                    paasPrintManageItemVO.setTemplateId(workOrderTemplateEntityExt.getId());
                    paasPrintManageItemVO.setMenuId(menuId);
                    paasPrintManageItemVO.setSaasMark(SaasMarkEnum.SAAS.getCode());
                    paasPrintManageItemVO.setId(workOrderTemplateEntityExt.getId());
                    paasPrintManageItemVO.setCategoryId(workOrderTemplateEntityExt.getCategoryId());
                    paasPrintHashMap.get(workOrderTemplateEntityExt.getCategoryId()).getSubMenuList().add(paasPrintManageItemVO);
                }
                list.addAll(paasPrintHashMap.values());
                break;
            }

            case PAAS: {
                params.put("del", DelEnum.NORMAL.getDel());
                List<PaasFormEntityExt> paasFormList = paasFormModel.list(params);
                if (paasFormList.isEmpty()) {
                    return paasPrintManageListVO;
                }
                for (PaasFormEntityExt formEntity : paasFormList) {
                    PaasPrintManageItemVO paasPrintManageItemVO = new PaasPrintManageItemVO();
                    paasPrintManageItemVO.setAlias(formEntity.getName());
                    paasPrintManageItemVO.setName(formEntity.getName());
                    paasPrintManageItemVO.setMenuId(formEntity.getMenuId());
                    paasPrintManageItemVO.setFormId(formEntity.getId());
                    paasPrintManageItemVO.setSaasMark(2);
                    list.add(paasPrintManageItemVO);
                }
                break;
            }
            default: {
                //非工单的所有saas业务
                params.put("saasMark", SaasMarkEnum.SAAS.getCode());
                // 谁漏的我也不知道，先写了再说 chenshan
                params.put("del", DelEnum.NORMAL.getDel());
                params.put("orderByStr", "sort asc");
                List<PaasMenuEntity> menuList = paasMenuModel.list(params);
                params.remove("orderByStr");
                if (menuList.isEmpty()) {
                    return paasPrintManageListVO;
                }
                //根据套餐获取当前公司套餐不能看到的菜单
                List<String> unSeeMenuList = packageHelp.getUnSeeMenuList(corpid);
                for (PaasMenuEntity menuEntity : menuList) {
                    String alias = menuEntity.getAlias();
                    if (Objects.equals(menuEntity.getSaasMark(), SaasMarkEnum.SAAS.getCode()) && unSeeMenuList.contains(alias)) {
                        continue;
                    }
                    PaasPrintManageItemVO paasPrintManageItemVO = new PaasPrintManageItemVO();
                    Long menuId = menuEntity.getId();
                    Long parentId = menuEntity.getParentId();

                    paasPrintManageItemVO.setAlias(alias);
                    paasPrintManageItemVO.setName(menuEntity.getName());
                    paasPrintManageItemVO.setMenuId(menuId);
                    paasPrintManageItemVO.setSaasMark(SaasMarkEnum.SAAS.getCode());
                    paasPrintManageItemVO.setId(menuEntity.getId());
                    paasPrintManageItemVO.setType(menuEntity.getType());
                    paasPrintManageItemVO.setParentId(menuEntity.getParentId());

                    if (Objects.equals(paasAppAlias, XbbRefTypeEnum.JXC.getAlias()) && Objects.equals(parentId, 0L)) {
                        // 可以拉到父菜单的没有打印模版的，应该还有，欢迎补充，补利哥的坑
                        if (ProductConstant.NO_PRINT_TEMPLATE.contains(menuEntity.getAlias())) {
                            continue;
                        }
                        // 存放一级菜单
                        list.add(paasPrintManageItemVO);
                    }
                    PrintMenuEnum printMenuEnum = PrintMenuEnum.getByAlias(alias);
                    if (printMenuEnum == null) {
                        // 不是打印菜单
                        continue;
                    }
                    if (Objects.equals(paasAppAlias, XbbRefTypeEnum.JXC.getAlias())) {
                        // 获取二级菜单，并放到容器中
                        if (Objects.isNull(menuMap.get(parentId))) {
                            List<PaasPrintManageItemVO> paasMenuList = new ArrayList<>();
                            paasMenuList.add(paasPrintManageItemVO);
                            menuMap.put(parentId, paasMenuList);
                        } else {
                            List<PaasPrintManageItemVO> paasMenuList = menuMap.get(parentId);
                            paasMenuList.add(paasPrintManageItemVO);
                            menuMap.put(parentId, paasMenuList);
                        }
                    } else {
                        list.add(paasPrintManageItemVO);
                    }
                }

                // 打印模版进销存分组
                if (Objects.equals(paasAppAlias, XbbRefTypeEnum.JXC.getAlias())) {
                    Iterator<PaasPrintManageItemVO> iterator = list.iterator();
                    // 分组下没有子菜单，直接删除
                    while (iterator.hasNext()) {
                        PaasPrintManageItemVO item = iterator.next();
                        if (Objects.nonNull(menuMap.get(item.getId())) && !menuMap.get(item.getId()).isEmpty()) {
                            // 将子菜单放入父菜单
                            item.setSubMenuList(menuMap.get(item.getId()));
                        } else if (Objects.equals(item.getType(), MenuTypeEnum.GROUP.getType())
                                && (Objects.isNull(menuMap.get(item.getId())) || menuMap.get(item.getId()).isEmpty())) {
                            iterator.remove();
                            continue;
                        }
                    }
                }

                params.put("del", DelEnum.NORMAL.getDel());
                params.put("saasMark", SaasMarkEnum.PAAS.getCode());
                List<PaasFormEntityExt> paasFormList = paasFormModel.list(params);
                Map<Long, PaasPrintManageItemVO> menuIdAndPrint = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                List<Long> formMenuList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                for (PaasFormEntityExt formEntity : paasFormList) {
                    PaasPrintManageItemVO paasPrintManageItemVO = new PaasPrintManageItemVO();
                    paasPrintManageItemVO.setAlias(formEntity.getName());
                    paasPrintManageItemVO.setName(formEntity.getName());
                    paasPrintManageItemVO.setMenuId(formEntity.getMenuId());
                    paasPrintManageItemVO.setFormId(formEntity.getId());
                    paasPrintManageItemVO.setBusinessType(formEntity.getBusinessType());
                    paasPrintManageItemVO.setSaasMark(SaasMarkEnum.PAAS.getCode());
                    paasPrintManageItemVO.setId(formEntity.getMenuId());
                    menuIdAndPrint.put(formEntity.getMenuId(), paasPrintManageItemVO);
                    formMenuList.add(formEntity.getMenuId());
                    list.add(paasPrintManageItemVO);
                }

                // 将自定义表单放入二级表单
                if (Objects.equals(paasAppAlias, XbbRefTypeEnum.JXC.getAlias())) {
                    Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                    map.put("corpid", corpid);
                    map.put("del", DelEnum.NORMAL.getDel());
                    map.put("appId", appId);
                    map.put("idIn", formMenuList);
                    List<PaasMenuEntity> newMenuList = paasMenuModel.list(map);
                    Map<Long, List<PaasPrintManageItemVO>> parentAndVO = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);

                    // 封装二级自定义表单parentAndVO
                    List<PaasPrintManageItemVO> nextPassList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                    newMenuList.forEach(item -> {
                        Long parentId = item.getParentId();
                        if (!Objects.equals(parentId, 0L)) {
                            if (Objects.isNull(parentAndVO.get(parentId))) {
                                List<PaasPrintManageItemVO> paasMenuList = new ArrayList<>();
                                paasMenuList.add(menuIdAndPrint.get(item.getId()));
                                parentAndVO.put(parentId, paasMenuList);
                            } else {
                                List<PaasPrintManageItemVO> paasMenuList = parentAndVO.get(parentId);
                                paasMenuList.add(menuIdAndPrint.get(item.getId()));
                                parentAndVO.put(parentId, paasMenuList);
                            }
                            nextPassList.add(menuIdAndPrint.get(item.getId()));
                        }
                    });

                    // 将二级自定义表单放入一级分组中
                    Iterator<PaasPrintManageItemVO> iterator = list.iterator();
                    while (iterator.hasNext()) {
                        PaasPrintManageItemVO item = iterator.next();
                        if (Objects.nonNull(parentAndVO.get(item.getId())) && !parentAndVO.get(item.getId()).isEmpty()) {
                            item.getSubMenuList().addAll(parentAndVO.get(item.getId()));
                        }
                        if (!nextPassList.isEmpty()) {
                            if (nextPassList.contains(item)) {
                                iterator.remove();
                                continue;
                            }
                        }
                    }
                }
                break;
            }
        }

        paasPrintManageListVO.setList(list);

        return paasPrintManageListVO;
    }

    /**
     * 获取可打印的字段
     *
     * @param formGetDTO 入参
     * @return PrintDisplayAttrVO
     */
    @Override
    public PrintDisplayAttrVO getDisPlayAttr(FormGetDTO formGetDTO) throws XbbException {
        FormGetVO formGetVO;
        PrintDisplayAttrVO printDisplayAttrVO = new PrintDisplayAttrVO();
        String formValue;
        Integer businessType = formGetDTO.getBusinessType();
        Integer sceneType = formGetDTO.getSceneType();
        try {
            Locale locale = LocaleContextHolder.getLocale();
            String lang = locale.toString();
            formValue = formFeignClient.getFormInfo(formGetDTO, lang);
        } catch (Exception e) {
            LOG.error("获取字段服务报错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, I18nStringConstant.FIELD_SERVICE_ERROR);
        }
        if (StringUtil.isEmpty(formValue)) {
            return printDisplayAttrVO;
        }
        JSONObject formValueJson = JsonHelperUtil.parseObject(formValue);
        formGetVO = JsonHelperUtil.parseObject(formValueJson.getString("result"), FormGetVO.class);
        formGetVO = formGetVO == null ? new FormGetVO() : formGetVO;
        List<FieldAttrEntity> formList = formGetVO.getExplainList();
        if (formList == null || formList.isEmpty()) {
            return printDisplayAttrVO;
        }
        // PaasFormEntity paasFormEntity = null;
        // if (Objects.equals(formGetDTO.getBusinessType(),XbbRefTypeEnum.WORK_ORDER)) {
        //     paasFormEntity = paasFormModel.getByKey(formGetVO.getFormId(),formGetDTO.getCorpid());
        // }
        // if (paasFormEntity == null) {
        //     throw new XbbException(ErrorCodeEnum.API_ERROR_350004);
        // }
        // businessType = paasFormEntity.getBusinessType();


        List<FieldAttrPojo> fieldAttrPojoList = new ArrayList<>();
        List<FieldAttrPojo> subFormAttrList = new ArrayList<>();
        if (Objects.equals(LocaleContextHolder.getLocale().getLanguage(), I18nStringConstant.ENGLISH_LANGUAGE)) {
            formList.forEach(fieldAttrEntity -> {
                String attrName = fieldAttrEntity.getAttrName();
                String attrNameEn = fieldAttrEntity.getAttrNameEn();
                fieldAttrEntity.setAttrName(attrName);
                fieldAttrEntity.setAttrNameEn(attrNameEn);
            });
        }
        formList.forEach((item) -> {
            // 去除不可打印的字段
            if (Objects.isNull(sceneType) || Objects.equals(PrintSceneTypeEnum.DEFAULT.getCode(), sceneType)) {
                if (!needPrintAttr(item)) {
                    return;
                }
            } else {
                // 先这样处理，其他场景也在else里判断
                if (!needPrintAttr4KitPrint(item)) {
                    return;
                }
            }
            Integer fieldType = item.getFieldType();
            // 封装返回格式
            FieldAttrPojo fieldAttrPojo = new FieldAttrPojo();
            BeanUtil.copyProperties(item, fieldAttrPojo);
            // 套打选项字段处理
            setSceneFiledAttrChecked(fieldAttrPojo, sceneType);
            // 子表单等与其他表单区分
            setFiledAttr(fieldAttrPojoList, subFormAttrList, fieldType, fieldAttrPojo, item.getSaasAttr());

        });

        // 加上特殊添加的打印字段
        if (Objects.isNull(sceneType) || Objects.equals(PrintSceneTypeEnum.DEFAULT.getCode(), sceneType)) {
            addOtherAttrs(businessType, fieldAttrPojoList);
        }
        //特殊处理回款单
        if (Objects.equals(XbbRefTypeEnum.PAYMENT_SHEET.getCode(), businessType)) {
            subFormForPaymentSheetAmount(subFormAttrList);
        } else if (Objects.equals(XbbRefTypeEnum.INVOICE.getCode(), businessType)) {
            //处理发票
            subFormForInvoice(subFormAttrList);
        } else if (Objects.equals(XbbRefTypeEnum.PAY_SHEET.getCode(), businessType)) {
            subFormForPaySheetAmount(subFormAttrList);
        } else if (Objects.equals(XbbRefTypeEnum.PURCHASE_INVOICE.getCode(), businessType)) {
            subFormForInvoicePurchase(subFormAttrList);
        } else if (Objects.equals(XbbRefTypeEnum.WORK_ORDER.getCode(), businessType)) {
            subFormForWorkOrder(subFormAttrList);
        } else if (Objects.equals(XbbRefTypeEnum.CUSTOMER_STATEMENT.getCode(), businessType)) {
            //处理对账单
            subFormForCustomerStatement(subFormAttrList);
        } else if (Objects.equals(XbbRefTypeEnum.RECEIPT_ORDER.getCode(), businessType)) {
            //处理对账单
            subFormForReceiptStatement(subFormAttrList);
        }

        printDisplayAttrVO.setDisPlayAttr(fieldAttrPojoList);
        printDisplayAttrVO.setSubFormAttr(subFormAttrList);

        return printDisplayAttrVO;
    }

    /**
     * 对账单的子表单进行特殊处理
     *
     * @param subFormAttrList
     */
    private void subFormForCustomerStatement(List<FieldAttrPojo> subFormAttrList) {
        // 移除其他的子表单
        subFormAttrList.clear();
        //往来明细
        PrintSpecialAttrEnum customerStatementDetailEnum = PrintSpecialAttrEnum.CUSTOMER_STATEMENT_DETAIL;
        FieldAttrPojo amountDetailPojo = new FieldAttrPojo(customerStatementDetailEnum.getAttr(), customerStatementDetailEnum.getAttrName(), customerStatementDetailEnum.getSaasAttr(), customerStatementDetailEnum.getFieldType());
        subFormAttrList.add(amountDetailPojo);
    }

    /**
     * 对回执单的子表单进行特殊处理
     *
     * @param subFormAttrList
     */
    private void subFormForReceiptStatement(List<FieldAttrPojo> subFormAttrList) {
        //往来明细
        PrintSpecialAttrEnum customerStatementDetailEnum = PrintSpecialAttrEnum.SERVICE_PROJECT;
        FieldAttrPojo amountDetailPojo = new FieldAttrPojo(customerStatementDetailEnum.getAttr(), customerStatementDetailEnum.getAttrName(), customerStatementDetailEnum.getSaasAttr(), customerStatementDetailEnum.getFieldType());
        subFormAttrList.add(amountDetailPojo);
    }

    /**
     * 处理工单动态,工单进展
     *
     * @param subFormAttrList
     */
    private void subFormForWorkOrder(List<FieldAttrPojo> subFormAttrList) {
        PrintSpecialAttrEnum workOrderProcess = PrintSpecialAttrEnum.WORK_ORDER_PROCESS;
        FieldAttrPojo processFieldAttr = new FieldAttrPojo(workOrderProcess.getAttr(), workOrderProcess.getAttrName(), workOrderProcess.getSaasAttr(), workOrderProcess.getFieldType());
        subFormAttrList.add(processFieldAttr);
        PrintSpecialAttrEnum workOrderDynamic = PrintSpecialAttrEnum.WORK_ORDER_DYNAMIC;
        FieldAttrPojo workOrderDynamicPojo = new FieldAttrPojo(workOrderDynamic.getAttr(), workOrderDynamic.getAttrName(), workOrderDynamic.getSaasAttr(), workOrderDynamic.getFieldType());
        subFormAttrList.add(workOrderDynamicPojo);
    }

    /**
     * 判断字段是否需要打印
     *
     * @param fieldAttrEntity 字段实体
     * @return 是否是打印字段
     */
    private boolean needPrintAttr(FieldAttrEntity fieldAttrEntity) {
        Integer fieldType = fieldAttrEntity.getFieldType();
        String saasAttr = fieldAttrEntity.getSaasAttr();
        Integer showType = fieldAttrEntity.getShowType();
        FieldTypeEnum fieldTypeEnum = FieldTypeEnum.getFieldTypeEnum(fieldType);
        if (fieldTypeEnum == null) {
            return false;
        }
        if (1 != fieldAttrEntity.getIsOpen()) {
            // 未启用的不展示
            return false;
        }
        if (1 != fieldAttrEntity.getVisible()) {
            // 不可见
            return false;
        }
        if (!ShowTypeEnum.detailShow(showType)) {
            // 详情不展示的字段，不打印
            return false;
        }
        if (PurchaseEnum.ADD_PAYPLAN.getSaasAttr().equals(saasAttr)) {
            // 付款计划不打印
            return false;
        }
        if (WorkReportDailyEnum.REVIEWER.getSaasAttr().equals(saasAttr) || WorkReportDailyEnum.IS_RESSUE.getSaasAttr().equals(saasAttr)) {
            // 工作报告 已读人列表 不打印
            return false;
        }
        // 22323 【成功部】打印模板无法关联合同毛利和合同毛利率字段　　机会成本毛利也不限制
//        boolean isOpportunityCost = SalesOpportunityEnum.COST.getSaasAttr().equals(saasAttr) || SalesOpportunityEnum.GROSS_PROFIT.getSaasAttr().equals(saasAttr)
//                                        || SalesOpportunityEnum.GROSS_PROFIT_RATE.getSaasAttr().equals(saasAttr);
//        if (isOpportunityCost) {
//            // 机会成本毛利等不打印
//            return false;
//        }

        boolean isNeed = true;
        switch (fieldTypeEnum) {
//            case IMAGE:
//                // 图片
//                isNeed =  false;
//                break;
            case UPLOAD:
                // 附件
                isNeed = false;
                break;
            case LINK_FORM:
                // 关联新建，列如：合同关联新建回款
                isNeed = false;
                break;
            case LOCATION:
            case SEPARATOR:
            case STAR:
            case MEMO:
            case FIRST_INTO_STAGE_TIME:
            case NOW_INTO_STAGE_TIME:
                // 定位，分割线，星级，描述文本不打印
                isNeed = false;
                break;
            default:
                break;
        }

        return isNeed;
    }

    /**
     * 套打等场景判断字段是否需要打印
     *
     * @param fieldAttrEntity 字段实体
     * @return
     * @throws
     * @author hongxiao
     * @date 2021-02-26 15:30
     * @version
     * @since
     */
    private boolean needPrintAttr4KitPrint(FieldAttrEntity fieldAttrEntity) {
        Integer fieldType = fieldAttrEntity.getFieldType();
        String saasAttr = fieldAttrEntity.getSaasAttr();
        Integer showType = fieldAttrEntity.getShowType();
        FieldTypeEnum fieldTypeEnum = FieldTypeEnum.getFieldTypeEnum(fieldType);
        if (fieldTypeEnum == null) {
            return false;
        }
        if (1 != fieldAttrEntity.getIsOpen()) {
            // 未启用的不展示
            return false;
        }
        if (1 != fieldAttrEntity.getVisible()) {
            // 不可见
            return false;
        }
        if (!ShowTypeEnum.detailShow(showType)) {
            // 详情不展示的字段，不打印
            return false;
        }
        if (PurchaseEnum.ADD_PAYPLAN.getSaasAttr().equals(saasAttr)) {
            // 付款计划不打印
            return false;
        }
        if (WorkReportDailyEnum.REVIEWER.getSaasAttr().equals(saasAttr) || WorkReportDailyEnum.IS_RESSUE.getSaasAttr().equals(saasAttr)) {
            // 工作报告 已读人列表 不打印
            return false;
        }

        boolean isNeed = true;
        switch (fieldTypeEnum) {
            // 附件
            case UPLOAD:
                // 关联新建，列如：合同关联新建回款
            case LINK_FORM:
                // 分割线
            case SEPARATOR:
                // 星级，描述文本不打印
            case MEMO:
                isNeed = false;
                break;
            default:
                break;
        }

        return isNeed;
    }


    /**
     * 添加其他打印字段
     *
     * @param businessType      业务类型
     * @param fieldAttrPojoList 普通字段列表
     */
    private void addOtherAttrs(Integer businessType, List<FieldAttrPojo> fieldAttrPojoList) {
        XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(businessType);
        if (xbbRefTypeEnum == null) {
            return;
        }
        switch (xbbRefTypeEnum) {
            case CONTRACT:
                addAttrPojoList(AdditionalPrintAttrEnum.CUSTOMER_ADDRESS, fieldAttrPojoList);
                addAttrPojoList(AdditionalPrintAttrEnum.CUSTOMER_PHONE, fieldAttrPojoList);
                addAttrPojoList(AdditionalPrintAttrEnum.CONTACT_PHONE, fieldAttrPojoList);
                break;
            case QUOTATION:
                addAttrPojoList(AdditionalPrintAttrEnum.CUSTOMER_ADDRESS, fieldAttrPojoList);
                addAttrPojoList(AdditionalPrintAttrEnum.CUSTOMER_PHONE, fieldAttrPojoList);
                addAttrPojoList(AdditionalPrintAttrEnum.CONTACT_PHONE, fieldAttrPojoList);
                addAttrPojoList(AdditionalPrintAttrEnum.CONTACT_ADDRESS, fieldAttrPojoList);
                break;
            case PURCHASE:
                // 供应商字段
                addAttrPojoList(AdditionalPrintAttrEnum.SUPPLIER_CONTACT_NAME, fieldAttrPojoList);
                addAttrPojoList(AdditionalPrintAttrEnum.SUPPLIER_PHONE, fieldAttrPojoList);
                addAttrPojoList(AdditionalPrintAttrEnum.SUPPLIER_ADDRESS, fieldAttrPojoList);
                addAttrPojoList(AdditionalPrintAttrEnum.SUPPLIER_MANAGER_NAME, fieldAttrPojoList);
                addAttrPojoList(AdditionalPrintAttrEnum.SUPPLIER_CONTACT_PHONE, fieldAttrPojoList);
                break;
            case RETURNED_PURCHASE:
                // 供应商字段
                addAttrPojoList(AdditionalPrintAttrEnum.SUPPLIER_CONTACT_NAME, fieldAttrPojoList);
                addAttrPojoList(AdditionalPrintAttrEnum.SUPPLIER_PHONE, fieldAttrPojoList);
                addAttrPojoList(AdditionalPrintAttrEnum.SUPPLIER_ADDRESS, fieldAttrPojoList);
                addAttrPojoList(AdditionalPrintAttrEnum.SUPPLIER_MANAGER_NAME, fieldAttrPojoList);
                addAttrPojoList(AdditionalPrintAttrEnum.SUPPLIER_CONTACT_PHONE, fieldAttrPojoList);
                break;
          /*  case INSTOCK:
                addAttrPojoList(AdditionalPrintAttrEnum.SUPPLIER,fieldAttrPojoList);
                break;
            case CONTRACT_OUTSTOCK:
            case WORK_ORDER_OUTSTOCK:
                addAttrPojoList(AdditionalPrintAttrEnum.CUSTOMER,fieldAttrPojoList);
                addAttrPojoList(AdditionalPrintAttrEnum.CUSTOMER_ADDRESS,fieldAttrPojoList);
                addAttrPojoList(AdditionalPrintAttrEnum.CUSTOMER_PHONE,fieldAttrPojoList);
                break;*/
            case TRANSFER:
                addAttrPojoList(AdditionalPrintAttrEnum.IN_USER_NAME, fieldAttrPojoList);
                addAttrPojoList(AdditionalPrintAttrEnum.OUT_USER_NAME, fieldAttrPojoList);
                break;
            case ASSEMBLE:
                addAttrPojoList(AdditionalPrintAttrEnum.IN_USER_NAME, fieldAttrPojoList);
                addAttrPojoList(AdditionalPrintAttrEnum.OUT_USER_NAME, fieldAttrPojoList);
                break;
            default:
                break;
        }

        // 添加“制表人” 特殊打印字段
        addAttrPojoList(AdditionalPrintAttrEnum.TABLE_MAKER, fieldAttrPojoList);
        // 添加“打印日期” 特殊打印字段
        addAttrPojoList(AdditionalPrintAttrEnum.PRINT_DATE_TIME, fieldAttrPojoList);
    }

    /**
     * 处理套打选项字段选中状态
     *
     * @param fieldAttrPojo
     * @param sceneType
     * @return
     * @throws
     * @author hongxiao
     * @date 2021-02-04 09:43
     * @version
     * @since
     */
    private void setSceneFiledAttrChecked(FieldAttrPojo fieldAttrPojo, Integer sceneType) {
        if (Objects.isNull(sceneType) || Objects.equals(PrintSceneTypeEnum.DEFAULT.getCode(), sceneType)) {
            return;
        }
        Integer fieldType = fieldAttrPojo.getFieldType();
        FieldTypeEnum fieldTypeEnum = FieldTypeEnum.getFieldTypeEnum(fieldType);
        if (fieldTypeEnum == null) {
            return;
        }
        List<ItemPoJo> items = fieldAttrPojo.getItems();
        if (Objects.isNull(items) || items.isEmpty()) {
            return;
        }
        switch (fieldTypeEnum) {
            case COMBO:
            case RADIO_GROUP:
            case CHECKBOX_GROUP:
            case COMBO_CHECK:
                items.forEach(itemPoJo -> itemPoJo.setChecked(true));
                break;
            default:
                break;
        }
    }

    /**
     * 区分 子表单等字段和普通字段
     *
     * @param fieldAttrPojoList 普通字段列表
     * @param subFormAttrList   子表单等特殊字段列表
     * @param fieldType         字段类型
     * @param fieldAttrPojo     展示字段pojo
     */
    private void setFiledAttr(List<FieldAttrPojo> fieldAttrPojoList, List<FieldAttrPojo> subFormAttrList, Integer fieldType, FieldAttrPojo fieldAttrPojo, String saasAttr) {
        FieldTypeEnum fieldTypeEnum = FieldTypeEnum.getFieldTypeEnum(fieldType);
        if (fieldTypeEnum == null) {
            return;
        }
        if (Objects.equals(WorkReportDailyEnum.THIS_STATISTIC.getSaasAttr(), saasAttr)) {
            // 工作报告：今日新增 saas中特殊表单，pro中好像是“业绩数据”这个字段？
            subFormAttrList.add(fieldAttrPojo);
            return;
        }
        /*

            合同：    合同产品 pro中不属于子表单，需特殊处理
            进销存相关表单： 关联产品
         */
        switch (fieldTypeEnum) {
            case SUB_FORM:
            case SELECT_PRODUCT:
            case SINGLE_SUB_FORM:
                subFormAttrList.add(fieldAttrPojo);
                break;
            default:
                fieldAttrPojoList.add(fieldAttrPojo);
                break;
        }
    }

    @Override
    public SubFormAttrDataVO getSubFormAttrData(SubFormAttrDataDTO subFormAttrDataDTO) throws XbbException {
        List<FieldAttrPojo> subFormAttrList = new ArrayList<>();
        List<FieldAttrPojo> sumAttrList = new ArrayList<>();
        String attr = subFormAttrDataDTO.getAttr();
        FormGetDTO formGetDTO = new FormGetDTO();
        BeanUtil.copyProperties(subFormAttrDataDTO, formGetDTO);
        String formValue;
        SubFormAttrDataVO subFormAttrDataVO = new SubFormAttrDataVO();
        Integer businessType = subFormAttrDataDTO.getBusinessType();
        //回款单
        boolean ifAmountDetail = Objects.equals(XbbRefTypeEnum.PAYMENT_SHEET.getCode(), businessType) &&
                Objects.equals(PrintSpecialAttrEnum.PAYMENT_SHEET_AMOUNT_DETAIL.getAttr(), attr);
        boolean ifWriteOffAmountDetail = Objects.equals(XbbRefTypeEnum.PAYMENT_SHEET.getCode(), businessType) &&
                Objects.equals(PrintSpecialAttrEnum.PAYMENT_SHEET_WRITE_OFF_AMOUNT_DETAIL.getAttr(), attr);
        if (ifAmountDetail || ifWriteOffAmountDetail) {
            disposePaymentSheetAmount(subFormAttrList, ifAmountDetail, ifWriteOffAmountDetail);
            subFormAttrDataVO.setAttrList(subFormAttrList);
            subFormAttrDataVO.setSumAttrList(sumAttrList);
            return subFormAttrDataVO;
        }
        //销项发票
        boolean ifInvoiceTotalMoneyDetail = Objects.equals(XbbRefTypeEnum.INVOICE.getCode(), businessType) &&
                Objects.equals(PrintSpecialAttrEnum.INVOICE_TOTAL_MONEY_DETAIL.getAttr(), attr);
        if (ifInvoiceTotalMoneyDetail) {
            disposeInvoiceTotalMoney(subFormAttrList);
            subFormAttrDataVO.setAttrList(subFormAttrList);
            subFormAttrDataVO.setSumAttrList(sumAttrList);
            return subFormAttrDataVO;
        }
        //付款单
        boolean ifPayAmountDetail = Objects.equals(XbbRefTypeEnum.PAY_SHEET.getCode(), businessType) &&
                Objects.equals(PrintSpecialAttrEnum.PAY_SHEET_AMOUNT_DETAIL.getAttr(), attr);
        boolean ifPayWriteOffAmountDetail = Objects.equals(XbbRefTypeEnum.PAY_SHEET.getCode(), businessType) &&
                Objects.equals(PrintSpecialAttrEnum.PAY_SHEET_WRITE_OFF_AMOUNT_DETAIL.getAttr(), attr);
        if (ifPayAmountDetail || ifPayWriteOffAmountDetail) {
            disposePaySheetAmount(subFormAttrList, ifPayAmountDetail, ifPayWriteOffAmountDetail);
            subFormAttrDataVO.setAttrList(subFormAttrList);
            subFormAttrDataVO.setSumAttrList(sumAttrList);
            return subFormAttrDataVO;
        }
        //进项发票
        boolean ifInvoicePurchaseTotalMoneyDetail = Objects.equals(XbbRefTypeEnum.PURCHASE_INVOICE.getCode(), businessType) &&
                Objects.equals(PrintSpecialAttrEnum.INVOICE_PURCHASE_TOTAL_MONEY_DETAIL.getAttr(), attr);
        if (ifInvoicePurchaseTotalMoneyDetail) {
            disposeInvoicePurchaseTotalMoney(subFormAttrList);
            subFormAttrDataVO.setAttrList(subFormAttrList);
            subFormAttrDataVO.setSumAttrList(sumAttrList);
            return subFormAttrDataVO;
        }
        //工单
        boolean workOrderDynamic = Objects.equals(XbbRefTypeEnum.WORK_ORDER.getCode(), businessType) && Objects.equals(PrintSpecialAttrEnum.WORK_ORDER_DYNAMIC.getAttr(), attr);
        if (workOrderDynamic) {
            subFormAttrList.add(new FieldAttrPojo(PrintSpecialAttrEnum.WORK_ORDER_PROCESS.getAttr(), PrintSpecialAttrEnum.WORK_ORDER_PROCESS.getAttrName(), PrintSpecialAttrEnum.WORK_ORDER_PROCESS.getAttr()));
            subFormAttrDataVO.setAttrList(subFormAttrList);
            subFormAttrDataVO.setSumAttrList(sumAttrList);
            return subFormAttrDataVO;
        }
        boolean workOrderProcess = Objects.equals(XbbRefTypeEnum.WORK_ORDER.getCode(), businessType) && Objects.equals(PrintSpecialAttrEnum.WORK_ORDER_PROCESS.getAttr(), attr);
        if (workOrderProcess) {
            subFormAttrList.add(new FieldAttrPojo(PrintSpecialAttrEnum.WORK_ORDER_DYNAMIC.getAttr(), PrintSpecialAttrEnum.WORK_ORDER_DYNAMIC.getAttrName(), PrintSpecialAttrEnum.WORK_ORDER_DYNAMIC.getAttr()));
            subFormAttrDataVO.setAttrList(subFormAttrList);
            subFormAttrDataVO.setSumAttrList(sumAttrList);
            return subFormAttrDataVO;
        }
        //对账单
        if (Objects.equals(XbbRefTypeEnum.CUSTOMER_STATEMENT.getCode(), businessType)) {
            disposeCustomerStatement(subFormAttrList);
            subFormAttrDataVO.setAttrList(subFormAttrList);
            FieldAttrPojo fieldAttrPojo = new FieldAttrPojo(CustomerStatementEnum.BALANCE_RECEIVABLE.getAttr(),
                    I18nMessageUtil.getMessage(BusinessConstant.CUSTOMER_STATEMENT_ATTRNAME), CustomerStatementEnum.BALANCE_RECEIVABLE.getSaasAttr());
            sumAttrList.add(fieldAttrPojo);
            subFormAttrDataVO.setSumAttrList(sumAttrList);
            return subFormAttrDataVO;
        }
        if (Objects.equals(XbbRefTypeEnum.RECEIPT_ORDER.getCode(), businessType)
                && (Objects.equals(PrintSpecialAttrEnum.SERVICE_PROJECT.getAttr(), attr)) || Objects.equals(ReceiptOrderEnum.SERVICE_PROJECT.getAttr(), attr)) {
            String printJson;
            try {
                printJson = workOrderPrintClient.getFormInfo(subFormAttrDataDTO, LocaleContextHolder.getLocale().toString());
            } catch (Exception e) {
                LOG.error("获取字段服务报错", e);
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, I18nStringConstant.FIELD_SERVICE_ERROR);
            }
            if (StringUtil.isEmpty(printJson)) {
                return subFormAttrDataVO;
            }
            JSONObject workOrderJson = JsonHelperUtil.parseObject(printJson);
            return JsonHelperUtil.parseObject(workOrderJson.getString(StringConstant.RESULT), SubFormAttrDataVO.class);
        }
        try {
            Locale locale = LocaleContextHolder.getLocale();
            String lang = locale.toString();
            formValue = formFeignClient.getFormInfo(formGetDTO, lang);
        } catch (Exception e) {
            LOG.error("获取字段服务报错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, I18nStringConstant.FIELD_SERVICE_ERROR);
        }
        if (StringUtil.isEmpty(formValue)) {
            return subFormAttrDataVO;
        }
        JSONObject formValueJson = JsonHelperUtil.parseObject(formValue);
        FormGetVO formGetVO = JsonHelperUtil.parseObject(formValueJson.getString("result"), FormGetVO.class);
        formGetVO = formGetVO == null ? new FormGetVO() : formGetVO;
        List<FieldAttrEntity> explainList = formGetVO.getExplainList();
        if (explainList == null || explainList.isEmpty()) {
            return subFormAttrDataVO;
        }
        FieldAttrEntity fieldAttrEntity = null;
        for (FieldAttrEntity item : explainList) {
            // 子表单attr匹配
            if (attr.equals(item.getAttr())) {
                fieldAttrEntity = item;
                subFormAttrDataVO.setAttr(attr);
                subFormAttrDataVO.setAttrName(item.getAttrName());
                subFormAttrDataVO.setSaasAttr(item.getSaasAttr());
                break;
            }
        }
        if (fieldAttrEntity == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100018, I18nStringConstant.SUB_FORM_NOT_EXIST);
        }

        Integer fieldType = fieldAttrEntity.getFieldType();
        FieldTypeEnum fieldTypeEnum = FieldTypeEnum.getFieldTypeEnum(fieldType);
        if (!FieldTypeEnum.SELECT_PRODUCT.equals(fieldTypeEnum)) {
            if (WorkReportDailyEnum.THIS_STATISTIC.getSaasAttr().equals(fieldAttrEntity.getSaasAttr())) {
                // 工作报告业绩数据特殊处理
                List<StatisticOptionEnum> statisticEnums = StatisticOptionEnum.getAllEnum();
                JSONObject statisticOptionSet = getWorkReportStatisticOptionSet(formGetVO, subFormAttrDataDTO.getCorpid());
                for (StatisticOptionEnum optionEnum : statisticEnums) {
                    // 封装返回格式
                    int option = StringUtil.toInt(statisticOptionSet.getString(optionEnum.getAttr()), 0);
                    if (option != 1) {
                        // 没有启用的不展示
                        continue;
                    }
                    FieldAttrPojo fieldAttrPojo = new FieldAttrPojo();
                    fieldAttrPojo.setAttr(optionEnum.getAttr());
                    fieldAttrPojo.setAttrName(optionEnum.getName());
                    fieldAttrPojo.setSaasAttr(optionEnum.getAttr());
                    subFormAttrList.add(fieldAttrPojo);
                }
            } else {
                // 普通子表单
                setSubFormAttr(subFormAttrList, fieldAttrEntity);
            }
        } else {
            // 设置关联产品字段的返回格式
            setSubFormProductAttr(subFormAttrDataDTO, attr, subFormAttrList, sumAttrList, fieldAttrEntity);
        }

        subFormAttrDataVO.setAttrList(subFormAttrList);
        subFormAttrDataVO.setSumAttrList(sumAttrList);
        return subFormAttrDataVO;
    }

    /**
     * 处理对账单里面的表格里面的标题字段
     *
     * @param subFormAttrList
     */
    private void disposeCustomerStatement(List<FieldAttrPojo> subFormAttrList) {
        List<PrintCustomerStatementDetailEnum> printCustomerStatementDetailEnums;
        printCustomerStatementDetailEnums = PrintCustomerStatementDetailEnum.getAllEnum();
        for (PrintCustomerStatementDetailEnum printCustomerStatementDetailEnum : printCustomerStatementDetailEnums) {
            if (printCustomerStatementDetailEnum == PrintCustomerStatementDetailEnum.PRODUCT) {
                // 关联产品字段
                FieldAttrPojo fieldAttrPojo = new FieldAttrPojo(printCustomerStatementDetailEnum.getAttr(), printCustomerStatementDetailEnum.getName(), printCustomerStatementDetailEnum.getAttr());
                List<FieldAttrPojo> productFields = new ArrayList<>();
                productFields.add(new FieldAttrPojo(SelectProductEnum.PRODUCT_NAME.getAttr(), SelectProductEnum.PRODUCT_NAME.getAttrName(), SelectProductEnum.PRODUCT_NAME.getAttr()));
                productFields.add(new FieldAttrPojo(SelectProductEnum.PRODUCT_NO.getAttr(), SelectProductEnum.PRODUCT_NO.getAttrName(), SelectProductEnum.PRODUCT_NO.getAttr()));
                productFields.add(new FieldAttrPojo(SelectProductEnum.SPECIFICATION.getAttr(), SelectProductEnum.SPECIFICATION.getAttrName(), SelectProductEnum.SPECIFICATION.getAttr()));
                productFields.add(new FieldAttrPojo(CustomerStatementProductEnum.SELLING_PRICE.getAttr(), CustomerStatementProductEnum.SELLING_PRICE.getAttrName(), CustomerStatementProductEnum.SELLING_PRICE.getAttr()));
                productFields.add(new FieldAttrPojo(CustomerStatementProductEnum.NUM.getAttr(), CustomerStatementProductEnum.NUM.getAttrName(), CustomerStatementProductEnum.NUM.getAttr()));
                productFields.add(new FieldAttrPojo(CustomerStatementProductEnum.SUBTOTAL.getAttr(), CustomerStatementProductEnum.SUBTOTAL.getAttrName(), CustomerStatementProductEnum.SUBTOTAL.getAttr()));
                fieldAttrPojo.setSecondFields(productFields);
                subFormAttrList.add(fieldAttrPojo);
            } else {
                subFormAttrList.add(new FieldAttrPojo(printCustomerStatementDetailEnum.getAttr(), printCustomerStatementDetailEnum.getName(), printCustomerStatementDetailEnum.getAttr()));
            }
        }
    }

    /**
     * 获取工作报告业绩统计设置
     *
     * @param formGetVO 表单回参
     * @param corpid    公司id
     * @return 业绩统计设置json
     */
    private JSONObject getWorkReportStatisticOptionSet(FormGetVO formGetVO, String corpid) {
        WorkReportSetEntity workReportSetEntity;
        JSONObject result = new JSONObject();
        FormEntityGetVO formEntityGetVO = formGetVO.getFormAttr();
        if (formEntityGetVO == null) {
            return result;
        }
        Integer businessType = formEntityGetVO.getBusinessType();
        if (businessType == null) {
            return result;
        }
        XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(businessType);
        WorkReportTypeEnum workReportTypeEnum = WorkReportTypeEnum.DAILY;
        switch (xbbRefTypeEnum) {
            case WORKREPORT_DAILY:
                workReportTypeEnum = WorkReportTypeEnum.DAILY;
                break;
            case WORKREPORT_WEEKLY:
                workReportTypeEnum = WorkReportTypeEnum.WEEKLY;
                break;
            case WORKREPORT_MONTHLY:
                workReportTypeEnum = WorkReportTypeEnum.MONTHLY;
                break;
            default:
                break;
        }
        workReportSetEntity = workReportSetModel.getByType(workReportTypeEnum.getType(), corpid);
        if (workReportSetEntity != null) {
            result = workReportSetEntity.getStatisticOption() == null ? new JSONObject() : workReportSetEntity.getStatisticOption();
        }
        return result;
    }

    /**
     * 设置普通子表单 字段的返回格式
     *
     * @param subFormAttrList 普通子表单列表
     * @param fieldAttrEntity 字段实体
     */
    private void setSubFormAttr(List<FieldAttrPojo> subFormAttrList, FieldAttrEntity fieldAttrEntity) {
        SubFormPoJo subFormPoJo = fieldAttrEntity.getSubForm();
        if (subFormPoJo == null) {
            return;
        }
        List<? extends FieldAttrEntity> items = subFormPoJo.getItems();
        if (items == null || items.isEmpty()) {
            return;
        }
        // 是否 工作报告-明日计划
        boolean isNextPlan = Objects.equals(WorkReportDailyEnum.NEXT_PLAN.getSaasAttr(), fieldAttrEntity.getSaasAttr());
        for (FieldAttrEntity obj : items) {
            String attr = obj.getAttr();
            // 字段回收站处理
            if (Objects.equals(obj.getIsOpen(), 2)) {
                continue;
            }
            if (isNextPlan && WorkReportPlanEnum.ID.getAttr().equals(attr)) {
                // 工作报告，明日计划去除计划id
                continue;
            }
            Integer fieldType = obj.getFieldType();
            FieldTypeEnum fieldTypeEnum = FieldTypeEnum.getFieldTypeEnum(fieldType);
            if (fieldTypeEnum == null || fieldTypeEnum.equals(FieldTypeEnum.UPLOAD)) {
                // 过滤字段
                continue;
            }

            // 封装返回格式
            FieldAttrPojo fieldAttrPojo = new FieldAttrPojo();
            fieldAttrPojo.setAttr(attr);
            fieldAttrPojo.setAttrName(obj.getAttrName());
            fieldAttrPojo.setSaasAttr(obj.getSaasAttr());
            fieldAttrPojo.setFieldType(fieldType);
            subFormAttrList.add(fieldAttrPojo);
        }
    }

    /**
     * 设置子表单-产品字段 的返回格式
     *
     * @param subFormAttrDataDTO 入参
     * @param attr               “关联产品”字段
     * @param subFormAttrList    普通字段
     * @param sumAttrList        汇总字段
     * @throws XbbException xbbException
     */
    private void setSubFormProductAttr(SubFormAttrDataDTO subFormAttrDataDTO, String attr, List<FieldAttrPojo> subFormAttrList, List<FieldAttrPojo> sumAttrList, FieldAttrEntity fieldAttrEntity) throws XbbException {
        SubFormPoJo subFormPoJo = fieldAttrEntity.getSubForm();
        if (subFormPoJo == null) {
            return;
        }
        List<FieldAttrEntity> fieldAttrList = (List<FieldAttrEntity>) subFormPoJo.getItems();
        if (fieldAttrList == null || fieldAttrList.isEmpty()) {
            return;
        }
        Integer businessType = subFormAttrDataDTO.getBusinessType();

        String formValue;
        try {
            ExplainMapLinkDataDTO explainMapLinkDataDTO = new ExplainMapLinkDataDTO();
            BeanUtil.copyProperties(subFormAttrDataDTO, explainMapLinkDataDTO);
            explainMapLinkDataDTO.setExplainList(fieldAttrList);
            Locale locale = LocaleContextHolder.getLocale();
            String lang = locale.toString();
            formValue = formFeignClient.explainMapByLinkData(explainMapLinkDataDTO, lang);
        } catch (Exception e) {
            LOG.error("获取字段服务报错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, I18nStringConstant.FIELD_SERVICE_ERROR);
        }
        if (StringUtil.isEmpty(formValue)) {
            return;
        }
        JSONObject formValueJson = JsonHelperUtil.parseObject(formValue);
        ExplainMapLinkDataVO explainMapLinkDataVO = JsonHelperUtil.parseObject(formValueJson.getString("result"), ExplainMapLinkDataVO.class);
        Map<Long, PaasFormExplainEntity> formExplainMap = explainMapLinkDataVO.getFormExplainMap();

        Map<Long, WorkOrderExplainEntity> workOrderExplainMap = explainMapLinkDataVO.getWorkOrderExplainMap();
        for (int i = 0; i < fieldAttrList.size(); i++) {
            FieldAttrEntity entity = fieldAttrList.get(i);
            if (Objects.equals(entity.getFieldType(), FieldTypeEnum.LINK_DATA.getType())) {
                LinkInfoPojo linkInfo = entity.getLinkInfo();
                List<LinkedAttrPoJo> linkedShowAttr = linkInfo.getLinkedShowAttr();
                if (CollectionUtils.isNotEmpty(linkedShowAttr)) {
                    for (int j = 0; j < linkedShowAttr.size(); j++) {
                        LinkedAttrPoJo linkedAttrPoJo = linkedShowAttr.get(j);
                        String explains;
                        if (!Objects.equals(XbbRefTypeEnum.WORK_ORDER.getCode(), linkInfo.getLinkBusinessType())) {
                            PaasFormExplainEntity paasFormExplainEntity = formExplainMap.get(linkInfo.getLinkFormId());
                            explains = Objects.isNull(paasFormExplainEntity) ? null : paasFormExplainEntity.getExplains();
                        } else {
                            WorkOrderExplainEntity paasFormExplainEntity = workOrderExplainMap.get(linkInfo.getLinkFormId());
                            explains = Objects.isNull(paasFormExplainEntity) ? null : paasFormExplainEntity.getExplains();
                        }
                        if (Objects.isNull(explains)) {
                            continue;
                        }
                        Map<String, FieldAttrEntity> linkExplain = ExplainUtil.getExplainMap(explains, null);
                        FieldAttrEntity linkedAttr = linkExplain.get(linkedAttrPoJo.getAttr());
                        if (Objects.nonNull(linkedAttr.getLinkDetail())) {
                            linkedAttr.setLinkDetail(null);
                        }
                        linkedAttr.setAttrName(linkedAttrPoJo.getAttrName());
                        linkedAttr.setAttr(linkInfo.getLinkBusinessType() + StringConstant.COMMA + linkedAttrPoJo.getAttr());
                        fieldAttrList.add(i + 1 + j, linkedAttr);
                    }
                }
            }
        }
        fieldAttrList.removeIf(field -> !UpdateDataTypeEnum.DETAIL.formatShow(field.getShowType()));
        // 过虑附件字段
        fieldAttrList.removeIf(field -> field.getFieldType().equals(FieldTypeEnum.UPLOAD.getType()));
        for (FieldAttrEntity attrEntity : fieldAttrList) {
            // 字段回收站处理
            if (Objects.equals(attrEntity.getIsOpen(), 2)) {
                continue;
            }
            // 封装返回格式
            FieldAttrPojo fieldAttrPojo = new FieldAttrPojo();
            fieldAttrPojo.setAttr(attrEntity.getAttr());
            fieldAttrPojo.setAttrName(attrEntity.getAttrName());
            fieldAttrPojo.setSaasAttr(attrEntity.getSaasAttr());
            fieldAttrPojo.setFieldType(attrEntity.getFieldType());
            subFormAttrList.add(fieldAttrPojo);
            // 放入基本单位和基本单位数量解释在数量的后面
            if (Objects.equals(attrEntity.getAttr(), SelectProductEnum.NUM.getAttr()) && Objects.equals(attrEntity.getIsRedundant(), 0) && StockConstant.MULTI_UNIT_TYPE_LIST.contains(businessType)) {
                fieldAttrPojo.setAttr(SelectProductEnum.BUSINESS_NUM.getAttr());
                fieldAttrPojo.setSaasAttr(SelectProductEnum.BUSINESS_NUM.getSaasAttr());
                fieldAttrPojo.setFieldType(SelectProductEnum.BUSINESS_NUM.getFieldType());
                FieldAttrPojo baseNumPojo = new FieldAttrPojo();
                baseNumPojo.setAttr(attrEntity.getAttr());
                baseNumPojo.setAttrName(MultiUnitConstant.UNIT_NUM);
                baseNumPojo.setSaasAttr(attrEntity.getSaasAttr());
                baseNumPojo.setFieldType(attrEntity.getFieldType());
                FieldAttrPojo baseUnitPojo = new FieldAttrPojo();
                baseUnitPojo.setAttr(SelectProductEnum.UNIT.getAttr());
                baseUnitPojo.setAttrName(MultiUnitConstant.BASE_UNIT);
                baseUnitPojo.setSaasAttr(SelectProductEnum.UNIT.getSaasAttr());
                baseUnitPojo.setFieldType(SelectProductEnum.UNIT.getFieldType());
                subFormAttrList.add(baseUnitPojo);
                subFormAttrList.add(baseNumPojo);
            }
            if (Objects.equals(attrEntity.getAttr(), SelectProductEnum.UNIT.getAttr()) && Objects.equals(attrEntity.getIsRedundant(), 0) && StockConstant.MULTI_UNIT_TYPE_LIST.contains(businessType)) {
                fieldAttrPojo.setAttr(SelectProductEnum.BUSINESS_UNIT.getAttr());
                fieldAttrPojo.setSaasAttr(SelectProductEnum.BUSINESS_UNIT.getSaasAttr());
                fieldAttrPojo.setFieldType(SelectProductEnum.BUSINESS_UNIT.getFieldType());
            }
        }
        // 手动添加产品图片
        List<Integer> outstockTypes = Arrays.asList(XbbRefTypeEnum.OTHER_OUTSTOCK.getCode(), XbbRefTypeEnum.CONTRACT_OUTSTOCK.getCode(), XbbRefTypeEnum.RETURNED_PURCHASE_OUTSTOCK.getCode(), XbbRefTypeEnum.WORK_ORDER_OUTSTOCK.getCode(), XbbRefTypeEnum.PRODUCTION_MATERIEL_OUTSTOCK.getCode(), XbbRefTypeEnum.OUTSTOCK.getCode());
        if (Objects.equals(XbbRefTypeEnum.CONTRACT.getCode(), businessType) || Objects.equals(XbbRefTypeEnum.SALES_OPPORTUNITY.getCode(), businessType)) {
            // 合同产品
            FieldAttrPojo amountAttrPojo = new FieldAttrPojo();
            amountAttrPojo.setAttr(BusinessConstant.TOTAL_PRODUCT_MONEY);
            amountAttrPojo.setAttrName(I18nMessageUtil.getMessage(I18nStringConstant.TOTAL_PRODUCT_PRICE));
            amountAttrPojo.setSaasAttr("amount");
            sumAttrList.add(amountAttrPojo);
        } else if (Objects.equals(XbbRefTypeEnum.QUOTATION.getCode(), businessType)) {
            FieldAttrPojo amountAttrPojo = new FieldAttrPojo();
            amountAttrPojo.setAttr(BusinessConstant.TOTAL_PRODUCT_MONEY);
            amountAttrPojo.setAttrName(I18nMessageUtil.getMessage(I18nStringConstant.TOTAL_PRODUCT_QUOTATIONS));
            amountAttrPojo.setSaasAttr("amount");
            sumAttrList.add(amountAttrPojo);
        } else if (Objects.equals(XbbRefTypeEnum.PURCHASE.getCode(), businessType)) {
            FieldAttrPojo amountAttrPojo = new FieldAttrPojo();
            amountAttrPojo.setAttr(BusinessConstant.TOTAL_PRODUCT_MONEY);
            amountAttrPojo.setAttrName(I18nMessageUtil.getMessage(I18nStringConstant.TOTAL_PRODUCT_PURCHASE_PRICE));
            amountAttrPojo.setSaasAttr("amount");
            sumAttrList.add(amountAttrPojo);
        } else if (Objects.equals(XbbRefTypeEnum.RECEIPT_ORDER.getCode(), businessType) || Objects.equals(XbbRefTypeEnum.WORK_ORDER_V2.getCode(), businessType)) {
            FieldAttrPojo amountAttrPojo = new FieldAttrPojo();
            amountAttrPojo.setAttr(BusinessConstant.TOTAL_PRODUCT_MONEY);
            amountAttrPojo.setAttrName(I18nMessageUtil.getMessage(I18nStringConstant.TOTAL_PRODUCT_PRICE));
            amountAttrPojo.setSaasAttr("amount");
            sumAttrList.add(amountAttrPojo);
        } else if (outstockTypes.contains(businessType)) {
            // 出库产品
            List<OutstockSaleRelativeConstantEnum> list = OutstockSaleRelativeConstantEnum.getAllEnum();
            for (OutstockSaleRelativeConstantEnum relativeConstantEnum : list) {
                // 封装返回格式
                FieldAttrPojo fieldAttrPojo = new FieldAttrPojo();
                fieldAttrPojo.setAttr(relativeConstantEnum.getAlias());
                fieldAttrPojo.setAttrName(relativeConstantEnum.getName());
                fieldAttrPojo.setSaasAttr(relativeConstantEnum.getAlias());
                // 除销售出库单外，其余出库单都不要‘产品售价合计’字段
                if (Objects.equals(relativeConstantEnum.getAlias(), OutstockSaleRelativeConstantEnum.SALE_PRICE_AMOUNT.getAlias()) && !Objects.equals(XbbRefTypeEnum.CONTRACT_OUTSTOCK.getCode(), businessType)) {
                    continue;
                }
                if (!Objects.equals(1, relativeConstantEnum.getProductShow())) {
                    sumAttrList.add(fieldAttrPojo);
                }
            }
        }

    }

    /**
     * 打印模板，获取关联产品字段解释
     *
     * @param subFormAttrDataDTO DTO入参
     * @param attr               表单字段
     * @return 服务返回值
     * @throws XbbException xbb异常
     */
    private JSONObject getProductExplainForExplain(SubFormAttrDataDTO subFormAttrDataDTO, String attr) throws XbbException {
        String productExplainValue;
        try {
            ProductExplainDTO productExplainDTO = new ProductExplainDTO();
            BeanUtil.copyProperties(subFormAttrDataDTO, productExplainDTO);
            XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(subFormAttrDataDTO.getBusinessType());
            productExplainDTO.setXbbRefTypeEnum(xbbRefTypeEnum);
            productExplainDTO.setAttr(attr);
            Locale locale = LocaleContextHolder.getLocale();
            String lang = locale.toString();
            productExplainValue = formFeignClient.getSelectProductExplainsForPrint(productExplainDTO, lang);
        } catch (Exception e) {
            LOG.error("打印获取产品字段服务报错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, I18nStringConstant.PRODUCT_EXPLAIN_ERROR);
        }
        JSONObject productExplainValueJson = JsonHelperUtil.parseObject(productExplainValue);
        if (ErrorCodeEnum.API_SUCCESS.getCode() != (int) productExplainValueJson.get(StringConstant.CODE)) {
            throw new XbbException(productExplainValueJson.getIntValue(StringConstant.CODE), productExplainValueJson.getString(StringConstant.KEY_ERROR_MSG));
        }
        return productExplainValueJson;
    }

    @Override
    public PaasPrintSaveVO delete(PaasPrintEditDTO paasPrintEditDTO) throws XbbException {
        String corpid = paasPrintEditDTO.getCorpid();
        // 登录用户
        UserEntity logUser = userModel.getByKey(paasPrintEditDTO.getUserId(), corpid);
        if (logUser == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001.getCode(), MessageConstant.USER_NOT_EXIST);
        }
        Long id = paasPrintEditDTO.getId();
        PaasPrintTemplateEntity templateEntity = paasPrintTemplateModel.getByKey(id, corpid);
        if (templateEntity == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, SystemErrorCodeEnum.API_ERROR_100028.getMsg());
        }
        PaasPrintSaveVO paasPrintSaveVO = new PaasPrintSaveVO();
        try {
            paasPrintTemplateModel.delete(id, paasPrintEditDTO.getCorpid());
        } catch (Exception e) {
            LOG.error("打印模板删除失败", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, SystemErrorCodeEnum.API_ERROR_100028.getMsg());
        }
        // 日志
        String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_DELETE_TEMPLATE), logUser.getName(), templateEntity.getName());
        mongoLogHelp.buildLog(corpid, logUser.getUserId(), logUser.getName(), OperateModuleTypeEnum.PAAS_PRINT, OperateTypeEnum.DELETE, id.toString(), templateEntity.getName(), memo, paasPrintEditDTO.getHttpHeader());

        paasPrintSaveVO.setId(id);
        return paasPrintSaveVO;
    }

    @Override
    public EnableVO enableFormList(TemplateDTO templateDTO) {
        Locale locale = LocaleContextHolder.getLocale();
        String lang = locale.toString();
        String formValue = null;
        if (Objects.equals(templateDTO.getBusinessType(), XbbRefTypeEnum.WORK_ORDER.getCode())) {
            formValue = formFeignClient.getWorkOrderFormEnableList(templateDTO, lang);
        } else {
            //新建打印模板只需要展示 启用的模板
            templateDTO.setPrintFlag(1);
            formValue = formFeignClient.getFormEnableList(templateDTO, lang);
        }
        EnableVO enableVO = new EnableVO();
        if (StringUtil.isEmpty(formValue)) {
            return enableVO;
        }
        JSONObject formValueJson = JsonHelperUtil.parseObject(formValue);
        enableVO = JsonHelperUtil.parseObject(formValueJson.getString("result"), EnableVO.class);
        return enableVO;
    }

    @Override
    public JSONArray getData(PaasPrintGetDataDTO paasPrintGetDataDTO) throws XbbException {
        String corpid = paasPrintGetDataDTO.getCorpid();
        UserEntity userEntity = userModel.getByKey(paasPrintGetDataDTO.getUserId(), corpid);
        if (userEntity == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100004, SystemErrorCodeEnum.API_ERROR_100004.getMsg());
        }
        Long formId = paasPrintGetDataDTO.getFormId();
        PaasFormEntity paasFormEntity = new PaasFormEntity();
        if (Objects.equals(paasPrintGetDataDTO.getBusinessType(), XbbRefTypeEnum.WORK_ORDER.getCode())) {
            WorkOrderFormEntityExt byKey = workOrderFormModel.getByKey(formId, paasPrintGetDataDTO.getCorpid());
            BeanUtil.copyProperties(byKey, paasFormEntity);
        } else {
            paasFormEntity = paasFormModel.getByKey(formId, corpid);
        }
        if (paasFormEntity == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100404, SystemErrorCodeEnum.API_ERROR_100404.getMsg());
        }
        paasPrintGetDataDTO.setDistributorMark(paasFormEntity.getDistributorMark());
        return printHelper.getValue(paasPrintGetDataDTO.getLoginUser(), paasPrintGetDataDTO, paasFormEntity);
    }

    @Override
    public JSONArray getDatas(PaasPrintGetDatasDTO paasPrintGetDatasDTO) throws XbbException {
        String corpid = paasPrintGetDatasDTO.getCorpid();
        UserEntity userEntity = userModel.getByKey(paasPrintGetDatasDTO.getUserId(), corpid);
        if (userEntity == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100004, SystemErrorCodeEnum.API_ERROR_100004.getMsg());
        }
        Long formId = paasPrintGetDatasDTO.getFormId();
        PaasFormEntity paasFormEntity = new PaasFormEntity();
        if (Objects.equals(paasPrintGetDatasDTO.getBusinessType(), XbbRefTypeEnum.WORK_ORDER.getCode())) {
            WorkOrderFormEntityExt byKey = workOrderFormModel.getByKey(formId, paasPrintGetDatasDTO.getCorpid());
            BeanUtil.copyProperties(byKey, paasFormEntity);
        } else {
            paasFormEntity = paasFormModel.getByKey(formId, corpid);
        }
        if (paasFormEntity == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100404, SystemErrorCodeEnum.API_ERROR_100404.getMsg());
        }
        return printHelper.getValues(paasPrintGetDatasDTO.getLoginUser(), paasPrintGetDatasDTO, paasFormEntity);
    }

    @Override
    public Boolean checkPrintBusiness(PaasPrintListDTO paasPrintListDTO) {
        PaasMenuEntity menuEntity = paasMenuModel.getByKey(paasPrintListDTO.getMenuId(), paasPrintListDTO.getCorpid());
        if (menuEntity == null) {
            return false;
        }
        String alias = menuEntity.getAlias();
        PrintMenuEnum printMenuEnum = PrintMenuEnum.getByAlias(alias);
        return printMenuEnum != null;
    }

    @Override
    public boolean checkPrintTemplateNum(PaasPrintListDTO paasPrintListDTO) throws XbbException {
        String corpid = paasPrintListDTO.getCorpid();
        int limitValue = PrintConstant.LIMIT_SIZE;
        CompanyConfigEntity companyConfig = companyConfigModel.getConfigEntity(corpid, CompanyConfigEnum.PRINT_LIMT_NUM.getAlias());
        if (companyConfig != null && !StringUtil.isEmpty(companyConfig.getConfigValue())) {
            limitValue = StringUtil.toInt(companyConfig.getConfigValue(), limitValue);
        }
        Long formId = paasPrintListDTO.getFormId();
        if (formId == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028.getCode(), I18nStringConstant.SELECT_FORM_TEMPLATE_FIRST);
        }
        Map<String, Object> printParam = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        printParam.put("corpid", corpid);
        printParam.put("del", 0);
        printParam.put("businessType", paasPrintListDTO.getBusinessType());
        printParam.put("formId", paasPrintListDTO.getFormId());
        Integer count = paasPrintTemplateModel.getEntitysCount(printParam);
        if (count != null && count >= limitValue) {
            throw new XbbException(PrintErrorCodeEnum.API_ERROR_2320012.getCode(), PrintErrorCodeEnum.API_ERROR_2320012.getMsg() + limitValue);
        }
        return true;
    }

    /**
     * 添加字段到字段列表中
     *
     * @param additionalPrintAttrEnum 额外字段枚举
     * @param fieldAttrPojoList       列表
     */
    private void addAttrPojoList(AdditionalPrintAttrEnum additionalPrintAttrEnum, List<FieldAttrPojo> fieldAttrPojoList) {
        FieldAttrPojo attrPojo = new FieldAttrPojo();
        attrPojo.setAttr(additionalPrintAttrEnum.getAttr());
        attrPojo.setAttrName(additionalPrintAttrEnum.getName());
        attrPojo.setSaasAttr(additionalPrintAttrEnum.getSaasAttr());
        // 额外加的字段默认单行输入
        attrPojo.setFieldType(FieldTypeEnum.TEXT.getType());
        fieldAttrPojoList.add(attrPojo);
    }

    /**
     * 编辑打印模板名称
     *
     * @param paasPrintNameEditDTO
     * @return
     * @throws
     * @author xingxing.xiao
     * @date 2019/10/09 12:20
     */
    @Override
    public PaasPrintNameEditVO updatePaasPrintTemplateName(PaasPrintNameEditDTO paasPrintNameEditDTO) throws XbbException {
        PaasPrintNameEditVO paasPrintNameEditVO = new PaasPrintNameEditVO();
        String corpid = paasPrintNameEditDTO.getCorpid();
        String loginUserName = paasPrintNameEditDTO.getLoginUserName();
        String userId = paasPrintNameEditDTO.getUserId();

        Long id = paasPrintNameEditDTO.getId();
        PaasPrintTemplateEntity printTemplateEntity = paasPrintTemplateModel.getByKey(id, corpid);
        if (printTemplateEntity == null) {
            throw new XbbException(PrintErrorCodeEnum.API_ERROR_2320011, PrintErrorCodeEnum.API_ERROR_2320011.getMsg());
        }
        String oldPrintName = printTemplateEntity.getName();
        BeanUtil.copyProperties(paasPrintNameEditDTO, printTemplateEntity);

        // 同一个菜单下的打印模板名称不能重复
        Map<String, Object> params = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        params.put("columns", "id, form_id, name");
        params.put("corpid", corpid);
        params.put("menuId", printTemplateEntity.getMenuId());
        params.put("name", paasPrintNameEditDTO.getName());
        params.put("del", DelEnum.NORMAL.getDel());
        params.put("idNot", id);
        Integer count = paasPrintTemplateModel.getEntitysCount(params);
        if (count != null && count > 0) {
            throw new XbbException(PrintErrorCodeEnum.API_ERROR_2320013, PrintErrorCodeEnum.API_ERROR_2320013.getMsg());
        }
        try {
            paasPrintTemplateModel.update(printTemplateEntity);
        } catch (Exception e) {
            LOG.error("updatePaasPrintTemplateName 出错", e);
            throw new XbbException(PrintErrorCodeEnum.API_ERROR_232003, PrintErrorCodeEnum.API_ERROR_232003.getMsg());
        }

        paasPrintNameEditVO.setId(id);

        // 日志
        String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_UPDATE_NEW_TEMPLATE), loginUserName, oldPrintName, paasPrintNameEditDTO.getName());
        mongoLogHelp.buildLog(corpid, userId, loginUserName, OperateModuleTypeEnum.PAAS_PRINT, OperateTypeEnum.EDIT,
                printTemplateEntity.getId().toString(), printTemplateEntity.getName(), memo, paasPrintNameEditDTO.getHttpHeader());

        return paasPrintNameEditVO;
    }

    /**
     * 打印模板名称查重(同一个菜单下的模板名称不能重复)
     *
     * @param paasPrintNameEditDTO
     * @return true 重复  false 不重复
     * @author xingxing.xiao
     * @date 2019/10/18 15:48
     */
    @Override
    public Boolean checkPrintTemplateName(PaasPrintNameEditDTO paasPrintNameEditDTO) throws XbbException {
        String corpid = paasPrintNameEditDTO.getCorpid();

        Map<String, Object> params = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        params.put("columns", "id, form_id, name");
        params.put("corpid", corpid);
        params.put("menuId", paasPrintNameEditDTO.getMenuId());
        params.put("name", paasPrintNameEditDTO.getName());
        params.put("del", DelEnum.NORMAL.getDel());
        Integer count = paasPrintTemplateModel.getEntitysCount(params);
        if (count != null && count > 0) {
            return true;
        }
        return false;
    }

    /**
     * 处理回款单的回款金额子表单的字段列表
     *
     * @param subFormAttrList 子表单的字段列表
     * @author 徐俊杰
     * @date 2019/12/3 10:47
     * @since v1.0
     */
    private void disposePaymentSheetAmount(List<FieldAttrPojo> subFormAttrList, boolean ifAmountDetail, boolean ifWriteOffAmountDetail) {
        List<PrintPaymentSheetAmountEnum> amountEnums;
        if (ifAmountDetail) {
            amountEnums = PrintPaymentSheetAmountEnum.getAmountEnum();
        } else if (ifWriteOffAmountDetail) {
            amountEnums = PrintPaymentSheetAmountEnum.getWriteOffAmountenum();
        } else {
            return;
        }
        for (PrintPaymentSheetAmountEnum amountEnum : amountEnums) {
            subFormAttrList.add(new FieldAttrPojo(amountEnum.getAttr(), amountEnum.getName(), amountEnum.getAttr()));
        }
    }

    /**
     * 处理付款单的付款金额子表单的字段列表
     *
     * @param subFormAttrList        子表单的字段列表
     * @param ifAmountDetail         是否金额明细
     * @param ifWriteOffAmountDetail 是否核销金额明细
     * @author 徐俊杰
     * @date 2020/3/21 16:35
     * @since v1.0
     */
    private void disposePaySheetAmount(List<FieldAttrPojo> subFormAttrList, boolean ifAmountDetail, boolean ifWriteOffAmountDetail) {
        List<PrintPaySheetAmountEnum> amountEnums;
        if (ifAmountDetail) {
            amountEnums = PrintPaySheetAmountEnum.getAmountEnum();
        } else if (ifWriteOffAmountDetail) {
            amountEnums = PrintPaySheetAmountEnum.getWriteOffAmountenum();
        } else {
            return;
        }
        for (PrintPaySheetAmountEnum amountEnum : amountEnums) {
            subFormAttrList.add(new FieldAttrPojo(amountEnum.getAttr(), amountEnum.getName(), amountEnum.getAttr()));
        }
    }

    /**
     * 处理发票的开票金额子表单的字段列表
     *
     * @param subFormAttrList 子表单的字段列表
     * @author 徐俊杰
     * @date 2019/12/6 11:24
     * @since v1.0
     */
    private void disposeInvoiceTotalMoney(List<FieldAttrPojo> subFormAttrList) {
        List<PrintInvoiceTotalMoneyEnum> totalMoneyEnums;
        totalMoneyEnums = PrintInvoiceTotalMoneyEnum.getAllEnum();
        for (PrintInvoiceTotalMoneyEnum totalMoneyEnum : totalMoneyEnums) {
            subFormAttrList.add(new FieldAttrPojo(totalMoneyEnum.getAttr(), totalMoneyEnum.getName(), totalMoneyEnum.getAttr()));
        }
    }

    /**
     * 处理进项发票的开票金额子表单的字段列表
     *
     * @param subFormAttrList 子表单的字段列表
     * @author 徐俊杰
     * @date 2020/3/21 16:37
     * @since v1.0
     */
    private void disposeInvoicePurchaseTotalMoney(List<FieldAttrPojo> subFormAttrList) {
        List<PrintInvoicePurchaseTotalMoneyEnum> totalMoneyEnums;
        totalMoneyEnums = PrintInvoicePurchaseTotalMoneyEnum.getAllEnum();
        for (PrintInvoicePurchaseTotalMoneyEnum totalMoneyEnum : totalMoneyEnums) {
            subFormAttrList.add(new FieldAttrPojo(totalMoneyEnum.getAttr(), totalMoneyEnum.getName(), totalMoneyEnum.getAttr()));
        }
    }

    /**
     * 处理disPlay字段中的subForm字段（回款单专用）
     *
     * @param subFormAttrList 子表单的字段列表
     * @author 徐俊杰
     * @date 2019/12/3 19:25
     * @since v1.0
     */
    private void subFormForPaymentSheetAmount(List<FieldAttrPojo> subFormAttrList) {
        //回款金额明细
        PrintSpecialAttrEnum amountDetailEnum = PrintSpecialAttrEnum.PAYMENT_SHEET_AMOUNT_DETAIL;
        FieldAttrPojo amountDetailPojo = new FieldAttrPojo(amountDetailEnum.getAttr(), amountDetailEnum.getAttrName(), amountDetailEnum.getSaasAttr(), amountDetailEnum.getFieldType());
        subFormAttrList.add(amountDetailPojo);
        //核销金额明细
        PrintSpecialAttrEnum writeOffAmountDetail = PrintSpecialAttrEnum.PAYMENT_SHEET_WRITE_OFF_AMOUNT_DETAIL;
        FieldAttrPojo writeOffAmountDetailPojo = new FieldAttrPojo(writeOffAmountDetail.getAttr(), writeOffAmountDetail.getAttrName(), writeOffAmountDetail.getSaasAttr(), writeOffAmountDetail.getFieldType());
        subFormAttrList.add(writeOffAmountDetailPojo);
    }

    /**
     * 处理disPlay字段中的subForm字段（付款单专用）
     *
     * @param subFormAttrList 子表单的字段列表
     * @author 徐俊杰
     * @date 2020/3/21 10:27
     * @since v1.0
     */
    private void subFormForPaySheetAmount(List<FieldAttrPojo> subFormAttrList) {
        //付款金额明细
        PrintSpecialAttrEnum amountDetailEnum = PrintSpecialAttrEnum.PAY_SHEET_AMOUNT_DETAIL;
        FieldAttrPojo amountDetailPojo = new FieldAttrPojo(amountDetailEnum.getAttr(), amountDetailEnum.getAttrName(), amountDetailEnum.getSaasAttr(), amountDetailEnum.getFieldType());
        subFormAttrList.add(amountDetailPojo);
        //付款核销金额明细
        PrintSpecialAttrEnum writeOffAmountDetail = PrintSpecialAttrEnum.PAY_SHEET_WRITE_OFF_AMOUNT_DETAIL;
        FieldAttrPojo writeOffAmountDetailPojo = new FieldAttrPojo(writeOffAmountDetail.getAttr(), writeOffAmountDetail.getAttrName(), writeOffAmountDetail.getSaasAttr(), writeOffAmountDetail.getFieldType());
        subFormAttrList.add(writeOffAmountDetailPojo);
    }

    /**
     * 处理disPlay字段中的subForm字段（发票专用）
     *
     * @param subFormAttrList 子表单的字段列表
     * @author 徐俊杰
     * @date 2019/12/6 10:54
     * @since v1.0
     */
    private void subFormForInvoice(List<FieldAttrPojo> subFormAttrList) {
        PrintSpecialAttrEnum totalMoneyDetailEnum = PrintSpecialAttrEnum.INVOICE_TOTAL_MONEY_DETAIL;
        FieldAttrPojo totalMoneyDetailPojo = new FieldAttrPojo(totalMoneyDetailEnum.getAttr(), totalMoneyDetailEnum.getAttrName(), totalMoneyDetailEnum.getSaasAttr(), totalMoneyDetailEnum.getFieldType());
        subFormAttrList.add(totalMoneyDetailPojo);
    }

    /**
     * 处理disPlay字段中的subForm字段（进项发票专用）
     *
     * @param subFormAttrList 子表单的字段列表
     * @author 徐俊杰
     * @date 2020/3/21 16:12
     * @since v1.0
     */
    private void subFormForInvoicePurchase(List<FieldAttrPojo> subFormAttrList) {
        PrintSpecialAttrEnum totalMoneyDetailEnum = PrintSpecialAttrEnum.INVOICE_PURCHASE_TOTAL_MONEY_DETAIL;
        FieldAttrPojo totalMoneyDetailPojo = new FieldAttrPojo(totalMoneyDetailEnum.getAttr(), totalMoneyDetailEnum.getAttrName(), totalMoneyDetailEnum.getSaasAttr(), totalMoneyDetailEnum.getFieldType());
        subFormAttrList.add(totalMoneyDetailPojo);
    }

    @Override
    public JSONArray getDataByProcess(PaasPrintGetDataByProcessDTO paasPrintGetDataByProcessDTO) throws XbbException {
        String corpid = paasPrintGetDataByProcessDTO.getCorpid();
        UserEntity userEntity = userModel.getByKey(paasPrintGetDataByProcessDTO.getUserId(), corpid);
        if (userEntity == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100004, SystemErrorCodeEnum.API_ERROR_100004.getMsg());
        }
        Long formId = paasPrintGetDataByProcessDTO.getFormId();
        PaasFormEntity paasFormEntity = new PaasFormEntity();
        if (Objects.equals(paasPrintGetDataByProcessDTO.getBusinessType(), XbbRefTypeEnum.WORK_ORDER.getCode())) {
            WorkOrderFormEntityExt byKey = workOrderFormModel.getByKey(formId, paasPrintGetDataByProcessDTO.getCorpid());
            BeanUtil.copyProperties(byKey, paasFormEntity);
        } else {
            paasFormEntity = paasFormModel.getByKey(formId, corpid);
        }
        if (paasFormEntity == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100404, SystemErrorCodeEnum.API_ERROR_100404.getMsg());
        }
        return printHelper.getValueByProcess(paasPrintGetDataByProcessDTO.getLoginUser(), paasPrintGetDataByProcessDTO, paasFormEntity);
    }

    @Override
    public JSONArray getDatasByProcess(PaasPrintGetDatasByProcessDTO paasPrintGetDatasByProcessDTO)
            throws XbbException {
        String corpid = paasPrintGetDatasByProcessDTO.getCorpid();
        UserEntity userEntity = userModel.getByKey(paasPrintGetDatasByProcessDTO.getUserId(), corpid);
        if (userEntity == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100004, SystemErrorCodeEnum.API_ERROR_100004.getMsg());
        }
        Long formId = paasPrintGetDatasByProcessDTO.getFormId();
        PaasFormEntity paasFormEntity = new PaasFormEntity();
        if (Objects.equals(paasPrintGetDatasByProcessDTO.getBusinessType(), XbbRefTypeEnum.WORK_ORDER.getCode())) {
            WorkOrderFormEntityExt byKey = workOrderFormModel.getByKey(formId, paasPrintGetDatasByProcessDTO.getCorpid());
            BeanUtil.copyProperties(byKey, paasFormEntity);
        } else {
            paasFormEntity = paasFormModel.getByKey(formId, corpid);
        }
        if (paasFormEntity == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100404, SystemErrorCodeEnum.API_ERROR_100404.getMsg());
        }
        return printHelper.getValuesByProcess(paasPrintGetDatasByProcessDTO.getLoginUser(), paasPrintGetDatasByProcessDTO, paasFormEntity);
    }

    @Override
    public PaasPrintSaveVO copy(PaasPrintEditDTO paasPrintEditDTO) throws XbbException {
        String corpid = paasPrintEditDTO.getCorpid();
        // 登录用户
        UserVO logUser = paasPrintEditDTO.getLoginUser();
        Long id = paasPrintEditDTO.getId();
        PaasPrintTemplateEntity templateEntity = paasPrintTemplateModel.getByKey(id, corpid);
        if (templateEntity == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, SystemErrorCodeEnum.API_ERROR_100028.getMsg());
        }
        // 校验数量是否超过上限
        int limitValue = PrintConstant.LIMIT_SIZE;
        CompanyConfigEntity companyConfig = companyConfigModel.getConfigEntity(corpid, CompanyConfigEnum.PRINT_LIMT_NUM.getAlias());
        if (companyConfig != null && !StringUtil.isEmpty(companyConfig.getConfigValue())) {
            limitValue = StringUtil.toInt(companyConfig.getConfigValue(), limitValue);
        }
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("corpid", corpid);
        param.put("del", 0);
        param.put("menuId", templateEntity.getMenuId());
        param.put("formId", templateEntity.getFormId());
        Integer count = paasPrintTemplateModel.getEntitysCount(param);
        if (count != null && count >= limitValue) {
            throw new XbbException(PrintErrorCodeEnum.API_ERROR_2320012.getCode(), PrintErrorCodeEnum.API_ERROR_2320012.getMsg() + limitValue);
        }
        // 查询全部的表单名字
        param.clear();
        param.put("columns", "id,name");
        param.put("appId", templateEntity.getAppId());
        param.put("menuId", templateEntity.getMenuId());
        param.put("formId", templateEntity.getFormId());
        param.put("corpid", corpid);
        param.put("startGroup", BasicConstant.ZERO);
        param.put("pageNumGroup", paasPrintEditDTO.getNum());
        param.put("del", DelEnum.NORMAL.getDel());
        List<PaasPrintTemplateEntity> printTemplateEntities = paasPrintTemplateModel.list(param);
        StringBuilder newName = new StringBuilder(templateEntity.getName() + "_");
        //选出要拼接的数字
        List<Integer> copyNum = new ArrayList<>();
        String substring;
        for (PaasPrintTemplateEntity item : printTemplateEntities) {
            if (item.getName().contains(newName)) {
                if (Objects.equals(item.getName().substring(0, newName.length()), newName.toString())) {
                    StringBuilder itemName = new StringBuilder(item.getName());
                    substring = itemName.substring(newName.length() + 1);
                    if (StringUtil.isNumeric(substring)) {
                        copyNum.add(Integer.valueOf(substring));
                    }
                }
            }
        }
        Collections.sort(copyNum);
        Integer sort = 1;
        for (Integer integer : copyNum) {
            if (Objects.equals(integer, sort)) {
                sort++;
            } else {
                break;
            }
        }

        PaasPrintTemplateEntity entity = new PaasPrintTemplateEntity();
        BeanUtil.copyProperties(templateEntity, entity);
        entity.setCreatorId(paasPrintEditDTO.getLoginUser().getUserId());
        String name = newName.append("_").append(sort).toString();
        entity.setName(name);
        entity.setId(null);

        PaasPrintSaveVO paasPrintSaveVO = new PaasPrintSaveVO();
        try {
            paasPrintTemplateModel.insert(entity);
        } catch (Exception e) {
            LOG.error("打印模板新增失败", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, SystemErrorCodeEnum.API_ERROR_100028.getMsg());
        }
        // 记录日志
        String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_ADD_PRINT_TEMPLATE), logUser.getName(), entity.getName());
        try {
            mongoLogHelp.buildLog(corpid, logUser.getUserId(), logUser.getName(), OperateModuleTypeEnum.PAAS_PRINT, OperateTypeEnum.NEW, entity.getId().toString(), entity.getName(), memo, paasPrintEditDTO.getHttpHeader());
        } catch (Exception e) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, I18nStringConstant.LOGGING_FAILED);
        }
        paasPrintSaveVO.setId(entity.getId());
        return paasPrintSaveVO;
    }

    /**
     * 给线上全部公司刷工单默认分类下默认表单刷默认打印模板
     *
     * @param baseDTO
     * @return
     * @throws XbbException
     */
    @Override
    public JSONObject initWorkOrderPrintTemplate(BaseDTO baseDTO) throws XbbException {
        Integer count = null;
        HashMap<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("isDefault", BasicConstant.ONE);
        param.put("del", DelEnum.NORMAL.getDel());
        param.put("columns", " id ");
        // 获取工单默认模板
        List<WorkOrderTemplateEntity> templateEntities = workOrderTemplateModel.findEntity(param);
        List<Long> templateIds = new ArrayList<>();
        templateEntities.forEach(item -> {
            templateIds.add(item.getId());
        });
        param.remove("columns");
        // 获取工单默认表单
        param.put("templateIdIn", templateIds);
        List<WorkOrderFormEntity> formEntities = workOrderFormModel.findEntitys(param);
        // 获取工单默认打印模板
        param.clear();
        param.put("corpid", "0");
        param.put("businessType", XbbRefTypeEnum.WORK_ORDER.getCode());
        param.put("del", DelEnum.NORMAL.getDel());
        List<PaasPrintTemplateEntity> defaultList = paasPrintTemplateModel.list(param);
        if (defaultList.isEmpty()) {
            // 数据库中没有存在默认模板配置
            return null;
        }
        PaasPrintTemplateEntity defaultTemplate = defaultList.get(0);
        // 添加工单默认打印分类
        List<PaasPrintTemplateEntity> defaultTemplateList = new ArrayList<>();
        Long now = DateUtil.getLong();
        for (WorkOrderFormEntity formEntity : formEntities) {
            PaasPrintTemplateEntity paasPrintTemplateEntity = new PaasPrintTemplateEntity();
            paasPrintTemplateEntity.setCorpid(formEntity.getCorpid());
            paasPrintTemplateEntity.setAppId(formEntity.getAppId());
            paasPrintTemplateEntity.setMenuId(formEntity.getMenuId());
            paasPrintTemplateEntity.setFormId(formEntity.getId());
            paasPrintTemplateEntity.setName("默认模板");
            paasPrintTemplateEntity.setEnable(1);
            paasPrintTemplateEntity.setHtml(defaultTemplate.getHtml());
            paasPrintTemplateEntity.setConfigInfo(defaultTemplate.getConfigInfo());
            paasPrintTemplateEntity.setBusinessType(XbbRefTypeEnum.WORK_ORDER.getCode());
            paasPrintTemplateEntity.setCreatorId(formEntity.getCorpid());
            paasPrintTemplateEntity.setUpdateTime(now);
            paasPrintTemplateEntity.setAddTime(now);
            paasPrintTemplateEntity.setDel(DelEnum.NORMAL.getDel());
            defaultTemplateList.add(paasPrintTemplateEntity);
        }
        try {
            count = paasPrintTemplateModel.insertBatch(defaultTemplateList);
        } catch (Exception e) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        JSONObject object = new JSONObject();
        object.put("修改记录数为", count);
        return object;
    }


    /**
     * 审批打印筛选列表
     *
     * @param processFormFilterDTO
     * @return
     * @throws XbbException
     */
    @Override
    public ProcessFormFilterVO formFilterForPrint(ProcessFormFilterDTO processFormFilterDTO) throws XbbException {
        ProcessFormFilterVO processFormFilterVO = new ProcessFormFilterVO();
        List<ProcessFormFilterPojo> formFilterPojoList = new ArrayList<>();
        UserVO userVO = processFormFilterDTO.getLoginUser();
        Set<String> saasPermissions = userVO.getPermSet();
        boolean isAdmin = userVO.isAdminOrBoss();
        String paasPermissions = userVO.getPaasPermissions();
        List<AppPermissionPojo> appPermissions = JSON.parseArray(paasPermissions, AppPermissionPojo.class);
        if (appPermissions == null) {
            appPermissions = new ArrayList<>();
        }
        Set<Long> menuPermSet = new HashSet<>();
        for (AppPermissionPojo appPermission : appPermissions) {
            appPermission.getModules().forEach(item -> menuPermSet.add(item.getId()));
        }
        // 记录
        Map<String, String> saasMenuNameMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        try {
            if (Objects.equals(processFormFilterDTO.getSaasMark(), SaasMarkEnum.SAAS.getCode())) {
                Integer appType = processFormFilterDTO.getSaasAppType();
                if (appType == null) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
                }
                List<String> saasAlias = new ArrayList<>();
                //已开启应用的alias
                List<String> openSaasAlias = new ArrayList<>();
                Map<String, Long> saasMenuIdMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                List<ProcessSaasFormEnum> businessTypeList = ProcessSaasFormEnum.getFormEnumList(appType);
                for (ProcessSaasFormEnum formEnum : businessTypeList) {
                    if (saasPermissions.contains(formEnum.getAlias())) {
                        saasAlias.add(ProcessSaasFormEnum.transfer2Saas(formEnum).getAlias());
                    }
                }
                Map<String, Object> param = BeanUtil.convertBean2Map(processFormFilterDTO, true);
                param.put("saasMark", SaasMarkEnum.SAAS.getCode());
                param.put("aliasIn", saasAlias);
                List<PaasMenuEntity> saasMenuList = paasMenuModel.list(param);
                // 原先复制代码删掉了，加回来
                if (saasAlias.contains(XbbRefTypeEnum.WORK_ORDER.getAlias())) {
                    param.remove("aliasIn");
                    param.remove("columns");
                    // workOrderTemplateModel.
                    List<WorkOrderFormEntity> workOrderFormEntities = workOrderFormModel.findEntitys(param);
                    workOrderFormEntities.forEach(item -> {
                        ProcessFormFilterPojo processFormFilterPojo = new ProcessFormFilterPojo();
                        BeanUtil.copyProperties(item, processFormFilterPojo);
                        processFormFilterPojo.setId(item.getTemplateId());
                        processFormFilterPojo.setBusinessType(XbbRefTypeEnum.WORK_ORDER.getCode());
                        processFormFilterPojo.setSaasMark(SaasMarkEnum.SAAS.getCode());
                        formFilterPojoList.add(processFormFilterPojo);
                    });
                    processFormFilterVO.setList(formFilterPojoList);
                    return processFormFilterVO;
                }
                saasMenuList.forEach((item) -> {
                    saasMenuIdMap.put(item.getAlias() + StringConstant.UNDER_LINE + item.getDistributorMark(), item.getId());
                    saasMenuNameMap.put(item.getAlias() + StringConstant.UNDER_LINE + item.getDistributorMark(), item.getName());
                    openSaasAlias.add(item.getAlias());
                });
                for (ProcessSaasFormEnum formEnum : businessTypeList) {
                    if (saasPermissions.contains(formEnum.getAlias()) && openSaasAlias.contains(formEnum.getAlias())) {
                        ProcessFormFilterPojo processFormFilterPojo = new ProcessFormFilterPojo();
                        processFormFilterPojo.setSaasMark(SaasMarkEnum.SAAS.getCode());
                        processFormFilterPojo.setBusinessType(XbbRefTypeEnum.transferBusinessType2Index(formEnum.getBusinessType()));
                        processFormFilterPojo.setName(saasMenuNameMap.get(ProcessSaasFormEnum.transfer2Saas(formEnum).getAlias() + StringConstant.UNDER_LINE + formEnum.getDistributorMark()));
                        processFormFilterPojo.setId(saasMenuIdMap.get(ProcessSaasFormEnum.transfer2Saas(formEnum).getAlias() + StringConstant.UNDER_LINE + formEnum.getDistributorMark()));
                        formFilterPojoList.add(processFormFilterPojo);
                    }
                }
                param.remove("aliasIn");
                param.put("saasMark", SaasMarkEnum.PAAS.getCode());
                List<PaasMenuEntity> menuEntityList = paasMenuModel.list(param);
                menuEntityList.forEach((item) -> {
                    if (isAdmin || menuPermSet.contains(item.getId())) {
                        ProcessFormFilterPojo processFormFilterPojo = new ProcessFormFilterPojo();
                        BeanUtil.copyProperties(item, processFormFilterPojo);
                        formFilterPojoList.add(processFormFilterPojo);
                    }
                });
            } else {
                // 未进行应用筛选
                if (processFormFilterDTO.getAppId() == null) {
                    List<String> saasAlias = new ArrayList<>();
                    Map<String, Long> saasMenuIdMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                    for (ProcessSaasFormEnum formEnum : ProcessSaasFormEnum.values()) {
                        if (saasPermissions.contains(formEnum.getAlias())) {
                            saasAlias.add(formEnum.getAlias());
                        }
                    }
                    Map<String, Object> param = BeanUtil.convertBean2Map(processFormFilterDTO, true);
                    param.put("saasMark", SaasMarkEnum.SAAS.getCode());
                    param.put("aliasIn", saasAlias);
                    List<PaasMenuEntity> saasMenuList = paasMenuModel.list(param);
                    saasMenuList.forEach((item) -> {
                        saasMenuIdMap.put(item.getAlias() + StringConstant.UNDER_LINE + item.getDistributorMark(), item.getId());
                        saasMenuNameMap.put(item.getAlias() + StringConstant.UNDER_LINE + item.getDistributorMark(), item.getName());

                    });
                    for (ProcessSaasFormEnum formEnum : ProcessSaasFormEnum.values()) {
                        if (saasPermissions.contains(formEnum.getAlias())) {
                            ProcessFormFilterPojo processFormFilterPojo = new ProcessFormFilterPojo();
                            processFormFilterPojo.setSaasMark(SaasMarkEnum.SAAS.getCode());
                            processFormFilterPojo.setBusinessType(XbbRefTypeEnum.transferBusinessType2Index(formEnum.getBusinessType()));
                            processFormFilterPojo.setName(saasMenuNameMap.get(ProcessSaasFormEnum.transfer2Saas(formEnum).getAlias() + StringConstant.UNDER_LINE + formEnum.getDistributorMark()));
                            processFormFilterPojo.setId(saasMenuIdMap.get(ProcessSaasFormEnum.transfer2Saas(formEnum).getAlias() + StringConstant.UNDER_LINE + formEnum.getDistributorMark()));
                            formFilterPojoList.add(processFormFilterPojo);
                        }
                    }
                }
                Map<String, Object> param = BeanUtil.convertBean2Map(processFormFilterDTO, true);
                param.put("saasMark", SaasMarkEnum.PAAS.getCode());
                List<PaasMenuEntity> menuEntityList = paasMenuModel.list(param);
                if (menuEntityList == null) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.MENU_NOT_EXIST);
                }

                menuEntityList.forEach((item) -> {
                    if (isAdmin || menuPermSet.contains(item.getId())) {
                        ProcessFormFilterPojo processFormFilterPojo = new ProcessFormFilterPojo();
                        BeanUtil.copyProperties(item, processFormFilterPojo);
                        formFilterPojoList.add(processFormFilterPojo);
                    }
                });
            }
            processFormFilterVO.setList(formFilterPojoList);
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("paasApp数据库查询出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return processFormFilterVO;
    }

    @Override
    public BaseVO templateSort(PaasPrintTemplateSortDTO paasPrintTemplateSortDT) throws XbbException {
        try {
            List<TemplateSortDTO> formList = paasPrintTemplateSortDT.getFormList();
            String corpid = paasPrintTemplateSortDT.getCorpid();
            List<PaasPrintTemplateEntity> paasPrintTemplateEntities = new ArrayList<>();
            BeanUtil.copyPropertiesList(formList, paasPrintTemplateEntities, PaasPrintTemplateEntity.class);
            paasPrintTemplateModel.updateBatch(paasPrintTemplateEntities, corpid);
        } catch (Exception e) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
        return new BaseVO();
    }

    private JSONArray setHtml4Product(String html) {
        JSONArray jsonArray = JsonHelperUtil.parseArray(html);
        try {
            // 老模板只有基本单位，没有业务单位，转换一下
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                if (jsonObject.containsKey("type") && jsonObject.getString("type").contains(FieldTypeEnum.SELECT_PRODUCT.getEsalias())) {
                    String displayAttrStr = jsonObject.getJSONObject("options").getString("dispalyAttrList");
                    if (!displayAttrStr.contains(SelectProductEnum.BUSINESS_NUM.getAttr()) && !displayAttrStr.contains(SelectProductEnum.BUSINESS_UNIT.getAttr())) {
                        displayAttrStr = displayAttrStr.replace(SelectProductEnum.NUM.getAttr(), SelectProductEnum.BUSINESS_NUM.getAttr()).replace(SelectProductEnum.UNIT.getAttr(), SelectProductEnum.BUSINESS_UNIT.getAttr());
                        JSONArray displayAttrArray = JsonHelperUtil.parseArray(displayAttrStr);
                        for (int j = 0; j < displayAttrArray.size(); j++) {
                            JSONObject attrObj = displayAttrArray.getJSONObject(j);
                            if (Objects.equals(attrObj.get("attr"), ProductPrintHelpEnum.NUM.getOldAttr())) {
                                attrObj.put("attr", SelectProductEnum.BUSINESS_NUM.getAttr());
                                displayAttrArray.set(j, attrObj);
                            } else if (Objects.equals(attrObj.get("attr"), ProductPrintHelpEnum.UNIT.getOldAttr())) {
                                attrObj.put("attr", SelectProductEnum.BUSINESS_UNIT.getAttr());
                                displayAttrArray.set(j, attrObj);
                            }
                        }
                        jsonObject.getJSONObject("options").put("dispalyAttrList", displayAttrArray);
                    }
                }
            }
        } catch (Exception e) {
            LOG.warn("转换出错");
        }
        return jsonArray;
    }

    /**
     * 获取默认套打模板
     *
     * @param corpid             公司id
     * @param kitPrintTemplateId 套打模板id
     * @param businessType       业务类型
     * @param paasPrintEditVO    返回pojo
     * @return
     * @throws
     * @author hongxiao
     * @date 2021-01-18 17:03
     * @version
     * @since
     */
    private void getKitPrintTemplate(String corpid, Long kitPrintTemplateId, Integer businessType, PaasPrintEditVO paasPrintEditVO) {
        // 没有选择模板
        if (Objects.isNull(kitPrintTemplateId) || Objects.equals(kitPrintTemplateId, BasicConstant.ZERO_LONG)) {
            return;
        }
        PaasKitPrintTemplateEntity kitPrintTemplate = paasKitPrintTemplateModel.getByKey(kitPrintTemplateId);
        if (Objects.isNull(kitPrintTemplate)) {
            return;
        }
        paasPrintEditVO.setCorpid(corpid);
        paasPrintEditVO.setBusinessType(businessType);
        paasPrintEditVO.setId(kitPrintTemplate.getId());
        paasPrintEditVO.setConfigInfo(JsonHelperUtil.parseObject(kitPrintTemplate.getConfigInfo()));
        paasPrintEditVO.setHtml(JsonHelperUtil.parseArray(kitPrintTemplate.getHtml()));
    }
}
